package com.suixun.service.impl;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.codehaus.jackson.map.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.authority.utils.DateUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.suixun.Constants;
import com.suixun.Result;
import com.suixun.controller.DeviceManage;
import com.suixun.dao.DeviceReserveMapper;
import com.suixun.dao.DevicelistMapper;
import com.suixun.dao.LogOperationMapper;
import com.suixun.dao.MqUseageMapper;
import com.suixun.dao.SchoolinfoMapper;
import com.suixun.dao.StdDeviceinfoMapper;
import com.suixun.dao.StdIotDeviceMapper;
import com.suixun.dao.StdIotSimMapper;
import com.suixun.dao.StdLostReportMapper;
import com.suixun.dao.StdObjectinfoMapper;
import com.suixun.dao.StdPeopleObjectMapper;
import com.suixun.dao.StdPeopleinfoMapper;
import com.suixun.dao.devicemanage.DeviceServiceDAO;
import com.suixun.dao.devicemanage.SimInfoServiceDAO;
import com.suixun.dao.model.PageGrid;
import com.suixun.dao.model.PageQueryModel;
import com.suixun.dao.parentmanage.ParentManageDAO;
import com.suixun.dao.studentmanage.StudentManageDAO;
import com.suixun.entity.BindwhitecardBatchModel;
import com.suixun.entity.ChangeWhiteCardModel;
import com.suixun.entity.DeviceInfo;
import com.suixun.entity.DeviceMessage;
import com.suixun.entity.DeviceReserve;
import com.suixun.entity.DeviceReserveExample;
import com.suixun.entity.Devicelist;
import com.suixun.entity.DevicelistExample;
import com.suixun.entity.LogOperation;
import com.suixun.entity.MqUseage;
import com.suixun.entity.MqUseageExample;
import com.suixun.entity.ParentInfo;
import com.suixun.entity.Schoolinfo;
import com.suixun.entity.SchoolinfoExample;
import com.suixun.entity.StdDeviceinfo;
import com.suixun.entity.StdDeviceinfoExample;
import com.suixun.entity.StdIotDevice;
import com.suixun.entity.StdIotDeviceExample;
import com.suixun.entity.StdIotSim;
import com.suixun.entity.StdIotSimExample;
import com.suixun.entity.StdLostReport;
import com.suixun.entity.StdLostReportExample;
import com.suixun.entity.StdObjectinfo;
import com.suixun.entity.StdObjectinfoExample;
import com.suixun.entity.StdPeopleObject;
import com.suixun.entity.StdPeopleObjectExample;
import com.suixun.entity.StdPeopleinfo;
import com.suixun.entity.StdPeopleinfoExample;
import com.suixun.entity.StdSimidauth;
import com.suixun.entity.ext.OpExtDevice;
import com.suixun.entity.factory.DeviceMessageFactory;
import com.suixun.entity.form.ParamForm;
import com.suixun.entity.jxt.JxtResult;
import com.suixun.entity.jxt.JxtStudent;
import com.suixun.entity.mongodb.DeviceCache;
import com.suixun.entity.page.PageModel;
import com.suixun.enums.APICode;
import com.suixun.excel.model.ExcelErrorRecord;
import com.suixun.excel.model.StudentModel;
import com.suixun.exception.OpServiceException;
import com.suixun.jxt.service.JxtService;
import com.suixun.queue.CMDDeal;
import com.suixun.queue.DeviceDeal;
import com.suixun.queue.SendMessageDeal;
import com.suixun.service.DevicePriceService;
import com.suixun.service.DeviceService;
import com.suixun.service.ObjectService;
import com.suixun.service.OnlinepayService;
import com.suixun.service.ParentService;
import com.suixun.service.StudentService;
import com.suixun.service.cache.CacheService;
import com.suixun.service.common.CommonService;
import com.suixun.service.mongodb.DeviceCacheService;
import com.suixun.thread.BatchImportCardThread;
import com.suixun.util.BeanUtil;
import com.suixun.util.Constant;
import com.suixun.util.DateUtil;
import com.suixun.util.ExcelUtil;
import com.suixun.util.HttpUtil;
import com.suixun.util.StringUtil;
import com.suixun.vo.ChangeDeviceVo;
import com.suixun.vo.DevicePriceVO;
import com.suixun.vo.DeviceVO;
import com.suixun.vo.RenewalOrderVO;
import com.suixun.vo.UnbindDeviceVo;

@Service
public class DeviceServiceImpl extends BaseServiceImpl implements DeviceService {
	protected Logger logger = LoggerFactory.getLogger(this.getClass());
	@Resource
	private DeviceServiceDAO divicedao;
	@Resource
	private LogOperationMapper logdao;
	@Resource
	private DevicelistMapper devicelistMapper;
	@Resource
	private StudentManageDAO studentDao;
	@Resource
	private StdPeopleObjectMapper stdPeopleObjectMapper;
	@Resource
	private StdObjectinfoMapper stdObjectinfoMapper;
	@Resource
	private StdDeviceinfoMapper stdDeviceinfoMapper;
	@Resource
	private ParentManageDAO parentManageDAO;
	@Resource
	private DeviceCacheService deviceCacheService;
	@Resource
	private CacheService cacheService;
	@Resource
	private LogOperationMapper logOperationMapper;
	@Resource
	private SimInfoServiceDAO simInfoServiceDAO;
	@Resource
	private DeviceReserveMapper deviceReserveMapper;
	@Resource
	private CommonService commonService;
	@Resource
	private StdPeopleinfoMapper stdPeopleinfoMapper;
	@Resource
	private ParentService parentService;
	@Resource
	private JxtService jxtService;
	@Resource
	private SchoolinfoMapper schoolinfoMapper;
	@Resource
	private SendMessageDeal sendMessageDeal;
	@Resource
	private StdLostReportMapper stdLostReportMapper;
	@Resource
	private StdIotSimMapper stdIotSimMapper;
	@Resource
	private OnlinepayService onlinepayService;
	@Resource
	private ObjectService objectService;
	@Resource
	private StdIotDeviceMapper stdIotDeviceMapper;
	@Resource
	private DevicePriceService devicePriceService;
	@Resource
	private MqUseageMapper mqUseageMapper;
	@Resource
	private DeviceDeal deviceDeal;
	@Resource
	private StudentService studentService;
	// 引入消息工厂
	private static DeviceMessageFactory messageFactory = new DeviceMessageFactory();

	// 查询设备列表
	@Override
	public List<DeviceVO> queryDevice(ParamForm paramForm) {
		List<DeviceVO> list = new ArrayList<>();
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("imei", paramForm.getImei());
		map.put("simid", paramForm.getSimid());

		// 先查询是否是缴费状态，如果是，则返回，不是则继续查询
		map.put("status", 3);
		PageQueryModel pqm = null;
		PageGrid pageGrid = null;
		pqm = new PageQueryModel(1, 1, null, null);
		pqm.setQueryParam(map);
		pageGrid = this.commonService.pageForObject("OpDeviceExtendSql.getPaymentPage", pqm);
		if (pageGrid == null || pageGrid.getRows() == null || pageGrid.getRows().size() == 0) {
			map.put("status", 2);
			pageGrid = this.commonService.pageForObject("OpDeviceExtendSql.getActivePage", pqm);
			if (pageGrid == null || pageGrid.getRows() == null || pageGrid.getRows().size() == 0) {
				map.put("status", 1);
				pageGrid = this.commonService.pageForObject("OpDeviceExtendSql.getInActivePage", pqm);
				if (pageGrid == null || pageGrid.getRows() == null || pageGrid.getRows().size() == 0) {
					map.put("status", 5);
					pageGrid = this.commonService.pageForObject("OpDeviceExtendSql.getRecyclePage", pqm);
					if (pageGrid == null || pageGrid.getRows() == null || pageGrid.getRows().size() == 0) {
						map.put("status", 4);
						pageGrid = this.commonService.pageForObject("OpDeviceExtendSql.getExpirePage", pqm);
					}
				}
			}
		}
		if (pageGrid == null || pageGrid.getRows() == null || pageGrid.getRows().size() == 0) {
			return list;
		}
		BeanUtil<OpExtDevice> beanUtil = new BeanUtil<OpExtDevice>();
		List<OpExtDevice> ents = null;
		try {
			ents = beanUtil.ListMap2JavaBean(pageGrid.getRows(), OpExtDevice.class);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}

		if (ents != null) {
			DeviceVO deviceVo = new DeviceVO();
			OpExtDevice tempDevice = ents.get(0);
			deviceVo.setFactory(tempDevice.getFactory());
			deviceVo.setDevicetype(String.valueOf(tempDevice.getDevicetype()));
			deviceVo.setMdtid(tempDevice.getMdtid());
			deviceVo.setTelephone(tempDevice.getTelephone());
			deviceVo.setCardid(tempDevice.getCardid());
			deviceVo.setStarttime(DateUtil.formatDateToString(tempDevice.getStarttime(), null));
			deviceVo.setEndtime(DateUtil.formatDateToString(tempDevice.getEndtime(), null));
			deviceVo.setPaystatus(String.valueOf(tempDevice.getPaystatus()));
			DevicePriceVO devicePrice = devicePriceService.getDevicePriceVo(tempDevice.getMdtid());
			deviceVo.setFee(String.valueOf(devicePrice.getDevicePrice()));
			deviceVo.setFee2(String.valueOf(devicePrice.getPackagePrice()));
			deviceVo.setSchoolname(tempDevice.getSchoolname());
			deviceVo.setPaystatus(tempDevice.getPaystatus() == null ? null : tempDevice.getPaystatus().toString());
			if ("3".equals(deviceVo.getPaystatus())) {
				RenewalOrderVO renewal = onlinepayService.getLastRenewalOrder(null, tempDevice.getMdtid());
				if (renewal != null) {
					deviceVo.setPaymoney(
							renewal.getRenewalmoney() == null ? null : renewal.getRenewalmoney().toString());
					deviceVo.setPaytime(renewal.getRenewaltime());
				}
			}
			if ("2".equals(deviceVo.getDevicetype())) {
				// 智能学生证，需要查看对应的实名认证信息
				StdSimidauth auth = objectService.getSimidAuthBySimid(deviceVo.getTelephone());
				if (auth != null) {
					deviceVo.setAuthstatus(
							auth.getStatus() == null ? null : Integer.parseInt(auth.getStatus().toString()));
					if ("3".equals(String.valueOf(auth.getStatus()))) {
						deviceVo.setAuthTime(DateUtils.parseDate2Str(auth.getAddtime()));
					}
				}
				// 获取来电防火墙信息
				Integer firewallStatus = getFirewallByMdtid(deviceVo.getMdtid());
				if (firewallStatus != null) {
					deviceVo.setFirewallstatus(firewallStatus);
				}
			}
			list.add(deviceVo);
		}
		return list;
	}

	// 分页查询设备列表
	@Override
	public PageModel<DeviceVO> queryDevicelistPage(ParamForm device) {

		PageModel<DeviceVO> pageModel = new PageModel<>();
		Map<String, Object> map = new HashMap<String, Object>();
		if (StringUtil.isEmpty(device.getStatus())) {
			device.setStatus("3");
		}
		map.put("imei", device.getImei());
		map.put("schoolname", device.getSchoolname());
		map.put("status", device.getStatus());
		map.put("simid", device.getSimid());
		map.put("devicetype", device.getDevicetype());
		map.put("teachertel", device.getTeachertel());
		map.put("province", device.getProvince());
		map.put("city", device.getCity());
		map.put("town", device.getTown());
		map.put("town", device.getStarttime());
		map.put("town", device.getEndtime());
		map.put("isExport", device.getIsExport());
		if (StringUtil.isEmpty(device.getPagenumber())) {
			device.setPagenumber("1");
		}
		if (StringUtil.isEmpty(device.getPagecount())) {
			device.setPagecount("15");
		}
		PageQueryModel pqm = null;
		PageGrid pageGrid = null;
		switch (device.getStatus()) {
		case "1":
			pqm = new PageQueryModel(Integer.parseInt(device.getPagenumber()), Integer.parseInt(device.getPagecount()),
					"a.addtime", "desc");
			pqm.setQueryParam(map);
			pageGrid = this.commonService.pageForObject("OpDeviceExtendSql.getInActivePage", pqm);
			break;
		case "2":
			pqm = new PageQueryModel(Integer.parseInt(device.getPagenumber()), Integer.parseInt(device.getPagecount()),
					"dls.updatetime", "desc");
			pqm.setQueryParam(map);
			pageGrid = this.commonService.pageForObject("OpDeviceExtendSql.getActivePage", pqm);
			break;
		case "3":
			pqm = new PageQueryModel(Integer.parseInt(device.getPagenumber()), Integer.parseInt(device.getPagecount()),
					"a.addtime", "desc");
			pqm.setQueryParam(map);
			pageGrid = this.commonService.pageForObject("OpDeviceExtendSql.getPaymentPage", pqm);
			break;
		case "4":
			pqm = new PageQueryModel(Integer.parseInt(device.getPagenumber()), Integer.parseInt(device.getPagecount()),
					"sdi.endtime", "desc");
			pqm.setQueryParam(map);
			pageGrid = this.commonService.pageForObject("OpDeviceExtendSql.getExpirePage", pqm);
			break;
		case "5":
			pqm = new PageQueryModel(Integer.parseInt(device.getPagenumber()), Integer.parseInt(device.getPagecount()),
					"dls.updatetime", "desc");
			pqm.setQueryParam(map);
			pageGrid = this.commonService.pageForObject("OpDeviceExtendSql.getRecyclePage", pqm);
			break;
		case "6":
			pqm = new PageQueryModel(Integer.parseInt(device.getPagenumber()), Integer.parseInt(device.getPagecount()),
					"sdi.endtime", "asc");
			pqm.setQueryParam(map);
			pageGrid = this.commonService.pageForObject("OpDeviceExtendSql.getExpiredFiveDaysPage", pqm);
			break;
		}

		BeanUtil<OpExtDevice> beanUtil = new BeanUtil<OpExtDevice>();
		List<OpExtDevice> ents = null;
		try {
			ents = beanUtil.ListMap2JavaBean(pageGrid.getRows(), OpExtDevice.class);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		if (ents != null) {
			List<DeviceVO> list = new ArrayList<>();
			DeviceVO deviceVo = null;
			DevicePriceVO devicePriceVo = null;
			for (OpExtDevice tempDevice : ents) {
				deviceVo = new DeviceVO();
				deviceVo.setFactory(tempDevice.getFactory());
				deviceVo.setDevicetype(String.valueOf(tempDevice.getDevicetype()));
				deviceVo.setMdtid(tempDevice.getMdtid());
				deviceVo.setTelephone(tempDevice.getTelephone());
				deviceVo.setCardid(tempDevice.getCardid());
				deviceVo.setStarttime(DateUtil.formatDateToString(tempDevice.getStarttime(), null));
				deviceVo.setEndtime(DateUtil.formatDateToString(tempDevice.getEndtime(), null));
				deviceVo.setPaystatus(String.valueOf(tempDevice.getPaystatus()));
				devicePriceVo = devicePriceService.getDevicePriceVo(tempDevice.getMdtid());
				deviceVo.setFee(String.valueOf(devicePriceVo.getDevicePrice()));
				deviceVo.setFee2(String.valueOf(devicePriceVo.getPackagePrice()));
				if ("true".equals(device.getIsExport())) {
					deviceVo.setParenttel(tempDevice.getPeopletel());
					deviceVo.setTeachertel(tempDevice.getTeachertel());
					deviceVo.setStudentname(tempDevice.getStudentname());
					deviceVo.setSchoolname(tempDevice.getSchoolname());
					deviceVo.setClassname(tempDevice.getClassname());
				}
				switch (tempDevice.getPaystatus()) {
				case 1:
					deviceVo.setPaystatus("未激活");
					break;
				case 2:
					deviceVo.setPaystatus("已激活");
					break;
				case 3:
					deviceVo.setPaystatus("已缴费");
					break;
				case 4:
					deviceVo.setPaystatus("已过期");
					break;
				case 5:
					deviceVo.setPaystatus("已回收");
					break;
				case 6:
					deviceVo.setPaystatus("五天后过期");
					break;
				}
				list.add(deviceVo);
			}
			pageModel.setPagesize(device.getPagecount() == null ? 15 : Integer.parseInt(device.getPagecount()));
			pageModel.setTotlepage(pageGrid.getRecords());
			pageModel.setCurrentpage(pageGrid.getPage());
			pageModel.setQueryresult(list);
		}
		return pageModel;
	}

	// 设备回收
	@Override
	@Transactional
	public int recycleDevice(String imei) {
		// 修改对应的sim卡状态为已回收状态
		Map<String, Object> map = new HashMap<>();
		map.put("imei", imei);
		List<DeviceInfo> templist = divicedao.queryDevice(map);
		String telephone = null;
		if (templist.size() > 0) {
			telephone = templist.get(0).getTelephone();
		}
		if (!imei.startsWith("8888") && !imei.startsWith("9999")) {
			map.put("telephone", telephone);
			simInfoServiceDAO.recycleSimInfo(map);
			// 修改std_iot_device表
			Devicelist device = new Devicelist();
			device.setSchoolname("");
			// device.setFee(new BigDecimal(0));
			// device.setFee2(new BigDecimal(0));
			device.setMdtid(imei);
			device.setStatus(-1);
			divicedao.updateDevice(device);

			// 将设备的套餐价设置为默认价
			DevicelistExample devicelistExample = new DevicelistExample();
			devicelistExample.createCriteria().andMdtidEqualTo(imei);
			Devicelist devicelist2 = new Devicelist();
			devicelist2.setFee2(devicePriceService.getDefaultPackagePrice());
			devicelistMapper.updateByExampleSelective(devicelist2, devicelistExample);

			StdIotDeviceExample stdIotDeviceExample = new StdIotDeviceExample();
			stdIotDeviceExample.createCriteria().andImeiLike(imei + "%");
			StdIotDevice stdIotDevice = new StdIotDevice();
			stdIotDevice.setFee2(devicePriceService.getDefaultPackagePrice());
			stdIotDevice.setSchoolname("");
			stdIotDeviceMapper.updateByExampleSelective(stdIotDevice, stdIotDeviceExample);
		} else {
			// 查询储备量中是否存在该数据，若有，则删除；
			if (imei.startsWith("8888") || imei.startsWith("9999")) {
				String cardid = imei.substring(4);
				DeviceReserveExample deviceReserveExample = new DeviceReserveExample();
				deviceReserveExample.createCriteria().andCardidEqualTo(cardid);
				deviceReserveMapper.deleteByExample(deviceReserveExample);
			}
		}

		// 判断设备是否已经解绑过的，若解绑过，则需要将std_deviceinfo的数据置为逻辑删除
		StdDeviceinfoExample stdDeviceinfoExample = new StdDeviceinfoExample();
		stdDeviceinfoExample.createCriteria().andMdtidEqualTo(imei).andObjectidEqualTo(0).andPeopleidEqualTo(0);
		StdDeviceinfo stdDeviceinfo = new StdDeviceinfo();
		stdDeviceinfo.setIsdeleted(1);
		stdDeviceinfo.setUpdatetime(new Date());
		stdDeviceinfoMapper.updateByExampleSelective(stdDeviceinfo, stdDeviceinfoExample);

		int result = 0;
		result = divicedao.deleteDeviceLists(imei);

		return result;
	}

	@Override
	@Transactional
	public int modifyDevicePhone(DeviceInfo info) {
		Map<String, Object> map = new HashMap<>();
		map.put("mdtid", info.getMdtid());
		map.put("simid", info.getTelephone());
		int result = studentDao.updateStudentInfo(map);
		// 查询学生id和对应的主监护人Id
		if (result == 1) {
			map.put("simid", "");
			// 刷新缓存
			StdObjectinfo student = studentDao.queryByParam(map);
			List<ParentInfo> parentList = parentManageDAO.queryByParam(map);
			StringBuffer peopleidsStringBuffer = new StringBuffer();
			if (parentList.size() > 0) {
				for (ParentInfo parent : parentList) {
					peopleidsStringBuffer.append(parent.getPeopleid()).append(",");
				}
			}
			String peopleids = peopleidsStringBuffer.substring(0, peopleidsStringBuffer.length() - 1).toString();
			// 清缓redis存
			cacheService.flushBabys(peopleids);
			cacheService.flushFullBaby(student.getPeopleid(), student.getObjectid());
			// 清除mongdb
			List<DeviceCache> deviceCaches = deviceCacheService
					.find(new Query(Criteria.where("mdtid").is(info.getMdtid())).limit(1));
			if (deviceCaches == null || deviceCaches.size() == 0) {
			} else {
				Update update = new Update();
				update.set("telephone", info.getTelephone());
				deviceCacheService.findAndModify(new Query(Criteria.where("mdtid").is(info.getMdtid())), update);
			}
		}
		result = divicedao.modifyDevicePhone(info);
		return result;
	}

	@Override
	@Transactional
	public int modifyCardId(DeviceInfo info) {
		Map<String, Object> map = new HashMap<>();
		// 先判断考勤卡号是否已存在
		map.put("cardid", info.getCardid());
		List<DeviceInfo> list = divicedao.queryDevice(map);
		if (list.size() > 0) {
			return -1;
		}
		int result = divicedao.modifyCardId(info);
		if (info.getMdtid().startsWith(Constant._13_56_MDTID_PREFIX)
				|| info.getMdtid().startsWith(Constant._2_4G_MDTID_PREFIX)) {
			map.put("mdtid", info.getMdtid());
			if (info.getMdtid().startsWith(Constant._13_56_MDTID_PREFIX)) {
				map.put("newMdtid",
						new StringBuffer().append(Constant._13_56_MDTID_PREFIX).append(info.getCardid()).toString());
				info.setTelephone(
						new StringBuffer().append(Constant._13_56_TEL_PREFIX).append(info.getCardid()).toString());
			} else if (info.getMdtid().startsWith(Constant._2_4G_MDTID_PREFIX)) {
				map.put("newMdtid",
						new StringBuffer().append(Constant._2_4G_MDTID_PREFIX).append(info.getCardid()).toString());
				info.setTelephone(
						new StringBuffer().append(Constant._2_4G_TEL_PREFIX).append(info.getCardid()).toString());
			}
			// 更新关联学生的imei
			map.put("simid", info.getTelephone());
			int isUpdate = studentDao.updateStudentInfo(map);
			if (isUpdate == 1) {
				map.put("simid", "");
				// 刷新缓存
				StdObjectinfo student = studentDao.queryByParam(map);
				List<ParentInfo> parentList = parentManageDAO.queryByParam(map);
				StringBuffer peopleidsStringBuffer = new StringBuffer();
				String peopleids = null;
				if (parentList.size() > 0) {
					for (ParentInfo parent : parentList) {
						peopleidsStringBuffer.append(parent.getPeopleid()).append(",");
					}
					peopleids = peopleidsStringBuffer.substring(0, peopleidsStringBuffer.length() - 1).toString();
				}
				if (student != null && peopleids != null) {
					// 清缓redis存
					cacheService.flushBabys(peopleids);
					cacheService.flushFullBaby(student.getPeopleid(), student.getObjectid());
					// 清除mongdb
					List<DeviceCache> deviceCaches = deviceCacheService
							.find(new Query(Criteria.where("mdtid").is(info.getMdtid())).limit(1));
					if (deviceCaches == null || deviceCaches.size() == 0) {
					} else {
						Update update = new Update();
						update.set("mdtid", new StringBuffer().append(Constant._13_56_MDTID_PREFIX)
								.append(info.getCardid()).toString());
						update.set("telephone", new StringBuffer().append(Constant._13_56_TEL_PREFIX)
								.append(info.getCardid()).toString());
						deviceCacheService.findAndModify(new Query(Criteria.where("mdtid").is(info.getMdtid())),
								update);
					}
				}
			}
			divicedao.updateDeviceInfo(map);
			divicedao.modifyDevicePhone(info);
			divicedao.updateMdtid(map);
			// 修改log_operation表中对应的mdtid
			logOperationMapper.updateByMdtid(map);
		}
		return result;
	}

	@Override
	@Transactional
	public int modifyEndTime(DeviceInfo info) {
		if (info.getMdtid().length() < 14) {
			return -1;
		}
		if (info.getMdtid().startsWith("8888") || info.getMdtid().startsWith("9999")) {
			return -2;
		}

		int result = divicedao.modifyEndTime(info);
		result = divicedao.modifyDeviceListEndTime(info);

		StdIotDevice stdIotDevice = new StdIotDevice();
		stdIotDevice.setEndtime(info.getEndtime());
		StdIotDeviceExample stdIotDeviceExample = new StdIotDeviceExample();
		stdIotDeviceExample.createCriteria().andImeiLike(info.getMdtid() + "%");
		stdIotDeviceMapper.updateByExampleSelective(stdIotDevice, stdIotDeviceExample);

		// 刷缓存 mongodb
		List<DeviceCache> deviceCaches = deviceCacheService
				.find(new Query(Criteria.where("mdtid").is(info.getMdtid())));
		if (deviceCaches != null && deviceCaches.size() > 0) {
			Update update = new Update();
			update.set("endtime", info.getEndtime());
			deviceCacheService.findAndModify(new Query(Criteria.where("mdtid").is(info.getMdtid())), update);
		}

		// redis缓存
		Map<String, String> m = new HashMap<String, String>();
		m.put("mdtid", info.getMdtid());
		List<Map<String, Object>> lst = commonService.selectList("StdDeviceinfoExtendSql.getDeviceUserInfo", m);
		if (lst != null && lst.size() > 0) {
			Map<String, Object> deviceUserInfo = lst.get(0);

			cacheService.flushBabys(String.valueOf(deviceUserInfo.get("peopleid")));
			cacheService.flushBaby(Integer.valueOf(deviceUserInfo.get("babyid").toString()));
			cacheService.flushGuardians(Integer.valueOf(deviceUserInfo.get("babyid").toString()));
		}
		return result;
	}

	@Override
	public PageModel<LogOperation> queryDeviceHistoryPage(ParamForm paramForm) {

		PageModel<LogOperation> pageModel = new PageModel<LogOperation>();
		if (StringUtil.isNotEmpty(paramForm.getImei())) {
			pageModel.getQueryparam().put("imei", paramForm.getImei());
		}
		Integer totleRows = divicedao.countHistoryRows(pageModel);
		pageModel.setTotlepage(totleRows);
		if (StringUtil.isNotEmpty(paramForm.getPagenumber())) {
			pageModel.setCurrentpage(Integer.parseInt(paramForm.getPagenumber()));
		}
		List<LogOperation> loglist = divicedao.queryDeviceHistoryPage(pageModel);
		if (loglist.size() > 0) {
			for (LogOperation logOperation : loglist) {
				StringBuffer content = new StringBuffer();
				if (logOperation.getOperation().contains("modifyDevicePhone")) {
					content = content.append(logOperation.getOperationername()).append(Constant.Operation.CONTENT_START)
							.append(logOperation.getMdtid()).append(Constant.Operation.CONTENT_MIDDLE_TEL)
							.append(logOperation.getOldvalue()).append(Constant.Operation.CONTENT_END)
							.append(logOperation.getNewvalue());
					logOperation.setOperation(content.toString());
				} else if (logOperation.getOperation().contains("modifyCardId")) {
					content = content.append(logOperation.getOperationername()).append(Constant.Operation.CONTENT_START)
							.append(logOperation.getMdtid()).append(Constant.Operation.CONTENT_MIDDLE_CARDID)
							.append(logOperation.getOldvalue()).append(Constant.Operation.CONTENT_END)
							.append(logOperation.getNewvalue());
					logOperation.setOperation(content.toString());
				} else if (logOperation.getOperation().contains("modifyEndTime")) {
					content = content.append(logOperation.getOperationername()).append(Constant.Operation.CONTENT_START)
							.append(logOperation.getMdtid()).append(Constant.Operation.CONTENT_MIDDLE_ENDTIME)
							.append(logOperation.getOldvalue()).append(Constant.Operation.CONTENT_END)
							.append(logOperation.getNewvalue());
					logOperation.setOperation(content.toString());
				}
			}
		}
		pageModel.setQueryresult(loglist);

		return pageModel;
	}

	@Override
	@Transactional
	public Integer unbindManyDevice(List<UnbindDeviceVo> vo) {
		for (UnbindDeviceVo dbd : vo) {
			ParamForm paramForm = new ParamForm();
			paramForm.setImei(dbd.getMdtid());
			// 解绑前的校验
			unbindManyDeviceVerify(dbd, paramForm);
			// 解绑
			Integer code = unbindDevice(paramForm);
			if (code != 1) {
				throw new RuntimeException(code.toString() + ",《" + dbd.getMdtid() + "，" + dbd.getMasterPhone() + "》");
			}
		}
		return 1;
	}

	/**
	 * 批量解绑,数据校验
	 * 
	 * @param dbd
	 *            需要校验的数据
	 * @param paramForm
	 *            通过返回的数据
	 * @return
	 */
	private boolean unbindManyDeviceVerify(UnbindDeviceVo dbd, ParamForm paramForm) {

		Integer peopleid = null;
		Integer objectidid = null;

		// 家长
		StdPeopleinfoExample spiExample = new StdPeopleinfoExample();
		spiExample.createCriteria().andPeopletelEqualTo(dbd.getMasterPhone()).andIsdeletedEqualTo(false);
		List<StdPeopleinfo> spiList = stdPeopleinfoMapper.selectByExample(spiExample);
		// 不存在返回提示
		if (CollectionUtils.isEmpty(spiList)) {
			throw new RuntimeException("手机号不存在!《" + dbd.getMdtid() + "，" + dbd.getMasterPhone() + "》");
		}
		peopleid = spiList.get(0).getPeopleid();
		paramForm.setPeopleid(peopleid.toString());

		// 小孩与设备
		StdDeviceinfoExample sdfExample = new StdDeviceinfoExample();
		sdfExample.createCriteria().andMdtidEqualTo(dbd.getMdtid()).andIsdeletedEqualTo(0);
		List<StdDeviceinfo> sdfList = stdDeviceinfoMapper.selectByExample(sdfExample);
		// 不存在返回提示
		if (CollectionUtils.isEmpty(sdfList)) {
			throw new RuntimeException("考情卡号不存在!《" + dbd.getMdtid() + "，" + dbd.getMasterPhone() + "》");
		}
		objectidid = sdfList.get(0).getObjectid();
		paramForm.setObjectid(objectidid.toString());

		// 判断是否主监护人
		if (!sdfList.get(0).getPeopleid().equals(peopleid)) {
			throw new RuntimeException("手机号非主监护人!《" + dbd.getMdtid() + "，" + dbd.getMasterPhone() + "》");
		}

		// 小孩与设备是否属于家长
		StdPeopleObjectExample spoExample = new StdPeopleObjectExample();
		spoExample.createCriteria().andPeopleidEqualTo(peopleid).andObjectidEqualTo(objectidid);
		List<StdPeopleObject> spoList = stdPeopleObjectMapper.selectByExample(spoExample);
		// 不存在返回提示
		if (CollectionUtils.isEmpty(spoList)) {
			throw new RuntimeException("此考情卡不属于该监护人!《" + dbd.getMdtid() + "，" + dbd.getMasterPhone() + "》");
		}
		return true;
	}

	@Override
	@Transactional
	public Integer changeDevice(List<ChangeDeviceVo> listVo) {
		if (!CollectionUtils.isEmpty(listVo)) {
			for (int i = 0; i < listVo.size(); i++) {
				changeDevice(listVo.get(i));
			}
		}
		return 1;
	}

	@Override
	@Transactional
	public Integer changeDevice(ChangeDeviceVo vo) {
		Object[] obj = changeDeviceVerify(vo);

		Devicelist olddevice = (Devicelist) obj[0];
		Devicelist newdevice = (Devicelist) obj[1];
		String cacheMdtid = "";

		// 处理卫小宝的考勤卡
		if (olddevice.getFactory().equals(Constant.Device.WEIXIAOBAO)) {
			// 查找升级前的考勤卡,并将cardid还原到以前状态
			String oldcardid = olddevice.getCardid();
			String mdtid1 = Constant._2_4G_MDTID_PREFIX + oldcardid;
			String mdtid2 = Constant._13_56_MDTID_PREFIX + oldcardid;
			Devicelist protoDevice = devicelistMapper.findProtoByMdtid(mdtid1, mdtid2);
			if (protoDevice.getId() != null) {
				protoDevice.setCardid(oldcardid);
				protoDevice.setUpdatetime(new Date());
				devicelistMapper.updateByPrimaryKeySelective(protoDevice);
			}
			// 将旧考勤卡cardid替换为新的卡cardid
			olddevice.setCardid(newdevice.getCardid());
			olddevice.setUpdatetime(new Date());
			devicelistMapper.updateByPrimaryKeySelective(olddevice);
			// 将新考勤卡cardid置空
			newdevice.setCardid("");
			newdevice.setUpdatetime(new Date());
			devicelistMapper.updateByPrimaryKeySelective(newdevice);
			cacheMdtid = olddevice.getMdtid();
		} else {// 处理非卫小宝的考勤卡
				// 查找旧卡在std_deviceinfo中的正常记录,如果存在则将mdtid跟换为新的,不存在则全部回滚
			StdDeviceinfoExample sdfExample = new StdDeviceinfoExample();
			sdfExample.createCriteria().andMdtidEqualTo(olddevice.getMdtid()).andIsdeletedEqualTo(0)
					.andObjectidNotEqualTo(0);
			List<StdDeviceinfo> sdfList = stdDeviceinfoMapper.selectByExample(sdfExample);
			if (CollectionUtils.isEmpty(sdfList)) {
				throw new RuntimeException("旧考情卡已被解绑或删除！《旧卡号:" + vo.getProtoOldCardid() + "》");
			}
			StdDeviceinfo sdInfo = sdfList.get(0);
			sdInfo.setMdtid(newdevice.getMdtid());
			sdInfo.setUpdatetime(new Date());
			stdDeviceinfoMapper.updateByPrimaryKeySelective(sdInfo);
			// 将旧卡重置为未激活
			olddevice.setStatus(0);
			olddevice.setIsinit(false);
			sdInfo.setUpdatetime(new Date());
			devicelistMapper.updateByPrimaryKeySelective(olddevice);
			// 将新卡激活
			newdevice.setStatus(1);
			newdevice.setIsinit(true);
			sdInfo.setUpdatetime(new Date());
			devicelistMapper.updateByPrimaryKeySelective(newdevice);
			// 修改学生考勤卡编号
			StdObjectinfoExample objInfoExample = new StdObjectinfoExample();
			objInfoExample.createCriteria().andMdtidEqualTo(olddevice.getMdtid()).andIsdeletedEqualTo(false);
			List<StdObjectinfo> objectList = stdObjectinfoMapper.selectByExample(objInfoExample);
			if (CollectionUtils.isEmpty(objectList)) {
				throw new RuntimeException("旧考情卡未绑定学生和家长，或已被删除！《旧卡号:" + vo.getProtoOldCardid() + "》");
			}
			StdObjectinfo objInfo = objectList.get(0);
			objInfo.setUpdatetime(new Date());
			objInfo.setMdtid(newdevice.getMdtid());
			objInfo.setSimid(newdevice.getTelephone());
			stdObjectinfoMapper.updateByPrimaryKeySelective(objInfo);
			cacheMdtid = newdevice.getMdtid();
		}

		// 清除缓存
		StdDeviceinfoExample devExample = new StdDeviceinfoExample();
		devExample.createCriteria().andMdtidEqualTo(cacheMdtid);
		List<StdDeviceinfo> devList = stdDeviceinfoMapper.selectByExample(devExample);
		StdDeviceinfo devinfo = devList.get(0);

		Map<String, Object> map = Maps.newHashMap();
		map.put("mdtid", devinfo.getMdtid());
		List<ParentInfo> parentList = parentManageDAO.queryByParam(map);
		List<Integer> peopleidList = new ArrayList<>();
		for (ParentInfo parent : parentList) {
			peopleidList.add(parent.getPeopleid());
		}
		// 清缓redis存
		cacheService.flushBabys(StringUtils.join(peopleidList, ","));
		cacheService.flushFullBaby(devinfo.getPeopleid(), devinfo.getObjectid());

		return 1;
	}

	/**
	 * 考情卡跟换前的校验
	 * 
	 * @param vo
	 */
	private Object[] changeDeviceVerify(ChangeDeviceVo vo) {
		Devicelist olddevice = null;
		Devicelist newdevice = null;
		// 校验旧考勤卡是否存在
		DevicelistExample oldExample = new DevicelistExample();
		oldExample.createCriteria().andMdtidEqualTo(vo.getOldCardid());
		List<Devicelist> oldlists = devicelistMapper.selectByExample(oldExample);
		if (CollectionUtils.isEmpty(oldlists)) {
			throw new RuntimeException("旧考勤卡不存在！《旧卡号:" + vo.getProtoOldCardid() + "》");
		}
		olddevice = oldlists.get(0);
		// 判断考勤卡是否升级
		if (StringUtils.isNotBlank(olddevice.getCardid())) {
			// 校验没有升级的考勤卡是否激活
			if (!olddevice.getIsinit() || olddevice.getStatus() == 0) {
				throw new RuntimeException("旧考勤卡未激活！《旧卡号:" + vo.getProtoOldCardid() + "》");
			}
		} else {
			// 校验已经升级的考勤卡是否存在并激活
			oldExample = new DevicelistExample();
			oldExample.createCriteria().andCardidEqualTo(vo.getProtoOldCardid()).andStatusEqualTo(1)
					.andIsinitEqualTo(true);
			oldlists = Lists.newArrayList();
			oldlists = devicelistMapper.selectByExample(oldExample);
			if (CollectionUtils.isEmpty(oldlists)) {
				throw new RuntimeException("旧考勤卡绑定的设备未激活！《旧卡号:" + vo.getProtoOldCardid() + "》");
			}
			olddevice = oldlists.get(0);
		}

		// 校验新考勤卡是否存在并且未使用
		DevicelistExample newExample = new DevicelistExample();
		newExample.createCriteria().andMdtidEqualTo(vo.getNewCardid()).andCardidEqualTo(vo.getProtoNewCardid())
				.andStatusEqualTo(0).andIsinitEqualTo(false);
		List<Devicelist> newlists = devicelistMapper.selectByExample(newExample);
		if (CollectionUtils.isEmpty(newlists)) {
			throw new RuntimeException("新考勤卡不存在或已被使用《" + "新卡号:" + vo.getProtoNewCardid() + "》");
		}
		newdevice = newlists.get(0);

		// 校验考勤卡是否投放于同一所学校
		if (!newdevice.getSchoolname().equals(olddevice.getSchoolname())) {
			throw new RuntimeException(
					"新考情卡与旧考情卡不属于同一所学校！《旧卡号:" + vo.getProtoOldCardid() + "，新卡号:" + vo.getProtoNewCardid() + "》");
		}
		return new Object[] { olddevice, newdevice };
	}

	/**
	 * <p>
	 * Title: unbindDevice
	 * </p>
	 * <p>
	 * 功能描述:解绑设备
	 * </p>
	 * 
	 * @param paramForm
	 * @return
	 */
	@Override
	@Transactional
	public Integer unbindDevice(ParamForm paramForm) {
		// 验证该设备是否未缴费
		/*
		 * PageModel<DeviceInfo> pageModel = new PageModel<DeviceInfo>();
		 * pageModel.getQueryparam().put("imei", paramForm.getImei());
		 * pageModel.getQueryparam().put("status", "3");
		 * pageModel.getQueryparam().put("isNotPage", "1"); List<DeviceInfo>
		 * deviceInfolist = divicedao.queryDeviceListByParam(pageModel); //
		 * 如果大于0，则已缴费，不能解绑 if (deviceInfolist != null && deviceInfolist.size() >
		 * 0) { return -1; }
		 */
		DevicelistExample devicelistExample = new DevicelistExample();
		devicelistExample.createCriteria().andMdtidEqualTo(paramForm.getImei());
		Devicelist devicelist = null;
		// 查询devicelist表中是否存在该mdtid
		List<Devicelist> devicelists = devicelistMapper.selectByExample(devicelistExample);
		if (devicelists != null && devicelists.size() > 0) {
			devicelist = devicelists.get(0);
		}
		StdObjectinfoExample stdObjectinfoExample = new StdObjectinfoExample();
		stdObjectinfoExample.createCriteria().andMdtidEqualTo(paramForm.getImei()).andIsdeletedEqualTo(false);
		List<StdObjectinfo> objectList = stdObjectinfoMapper.selectByExample(stdObjectinfoExample);
		if (CollectionUtils.isEmpty(objectList)) {
			return -2;
		}
		JxtResult jxtResult = jxtService.cancelStudent(objectList.get(0).getJxtBabyid());
		if (jxtResult == null || jxtResult.getCode() != 0) {
			return -2;
		}

		// 重置devicelists表数据
		if (devicelist != null) {
			if (devicelist.getDevicetype().equals(1)) {
				devicelist = new Devicelist();
				devicelist.setIsinit(false);
			} else {
				devicelist = new Devicelist();
				devicelist.setIsinit(false);
				devicelist.setStatus(0);
			}

			devicelist.setUpdatetime(new Date());
			// 解除devicelists表
			devicelistMapper.updateByExampleSelective(devicelist, devicelistExample);
		}
		Map<String, Object> map = new HashMap<>();
		map.put("mdtid", paramForm.getImei());
		List<ParentInfo> parentList = parentManageDAO.queryByParam(map);
		List<Integer> peopleidList = new ArrayList<>();
		if (parentList.size() > 0) {
			for (ParentInfo parent : parentList) {
				peopleidList.add(parent.getPeopleid());
			}
		}
		// String peopleids = peopleidsStringBuffer.substring(0,
		// peopleidsStringBuffer.length() - 1).toString();
		// 清缓redis存
		cacheService.flushBabys(StringUtils.join(peopleidList, ","));
		cacheService.flushFullBaby(Integer.parseInt(paramForm.getPeopleid()),
				Integer.parseInt(paramForm.getObjectid()));
		StdPeopleObjectExample stdPeopleObjectExample = new StdPeopleObjectExample();
		// 解除std_people_object表
		stdPeopleObjectExample.createCriteria().andObjectidEqualTo(Integer.parseInt(paramForm.getObjectid()));
		stdPeopleObjectMapper.deleteByExample(stdPeopleObjectExample);
		// 解除std_objectinfo表
		StdObjectinfo stdObjectinfo = new StdObjectinfo();
		stdObjectinfo.setObjectid(Integer.parseInt(paramForm.getObjectid()));
		// 逻辑删除objectinfo里对应的数据
		stdObjectinfo.setIsdeleted(true);
		stdObjectinfoMapper.updateByPrimaryKeySelective(stdObjectinfo);
		// 解除std_deviceinfo表
		StdDeviceinfoExample stdDeviceinfoExample = new StdDeviceinfoExample();
		stdDeviceinfoExample.createCriteria().andObjectidEqualTo(Integer.parseInt(paramForm.getObjectid()))
				.andIsdeletedEqualTo(0);
		List<StdDeviceinfo> list = stdDeviceinfoMapper.selectByExample(stdDeviceinfoExample);
		if (list != null && list.size() > 0) {
			// Integer deviceid = list.get(0).getDeviceid();

			StdDeviceinfo stdDeviceinfo = new StdDeviceinfo();
			// 更新修改日期
			stdDeviceinfo.setUpdatetime(new Date());
			// 设置peopeleid=0
			stdDeviceinfo.setPeopleid(0);
			// 设置objectid=0
			stdDeviceinfo.setObjectid(0);
			stdDeviceinfoMapper.updateByExampleSelective(stdDeviceinfo, stdDeviceinfoExample);
			// 清除mongdb
			// 推送管理员解绑
			DeviceCache deviceCache = null;
			List<DeviceCache> deviceCaches = deviceCacheService
					.find(new Query(Criteria.where("mdtid").is(paramForm.getImei())).limit(1));
			if (deviceCaches == null || deviceCaches.size() == 0) {
			} else {
				deviceCache = deviceCaches.get(0);
			}
			if (deviceCache != null)
				CMDDeal.sendcancel("cancelbaby", Integer.parseInt(paramForm.getPeopleid()),
						Integer.parseInt(paramForm.getObjectid()), deviceCache.getTelephones(), paramForm.getImei(),
						deviceCache.getBabyname());
		}
		cacheService.refreshDeviceCache(paramForm.getImei(), Integer.parseInt(paramForm.getPeopleid()),
				Integer.parseInt(paramForm.getObjectid()), true);
		return 1;
	}

	/**
	 * <p>
	 * Title: addLogOperation
	 * </p>
	 * <p>
	 * 功能描述:记录修改日志
	 * </p>
	 * 
	 * @param info
	 * @return
	 */
	@Override
	public Integer addLogOperation(LogOperation logOperation) {
		Integer isAdd = logOperationMapper.insert(logOperation);
		return isAdd;
	}

	/**
	 * 导出Excel
	 * 
	 * @throws Exception
	 */
	@Override
	public HSSFWorkbook exportDeviceList(ParamForm device) throws Exception {
		ArrayList<String> listParm = new ArrayList<String>();
		listParm.add(Constant.Excel.DEVICE_TYPE);
		listParm.add(Constant.Excel.FACTORY);
		listParm.add(Constant.Excel.IMEI);
		listParm.add(Constant.Excel.TELEPHONE);
		listParm.add(Constant.Excel.CARD);
		listParm.add(Constant.Excel.STUDENTNAME);
		listParm.add(Constant.Excel.GRADE);
		listParm.add(Constant.Excel.SCHOOLNAME);
		listParm.add(Constant.Excel.TEACHERTEL);
		listParm.add(Constant.Excel.PARENTTEL);
		listParm.add(Constant.Excel.ACTIVE_DATE);
		listParm.add(Constant.Excel.VALID_DATE);
		listParm.add(Constant.Excel.PAY_STATUS);
		listParm.add(Constant.Excel.FEE);
		listParm.add(Constant.Excel.FEE2);
		List<List<String>> listValue = new LinkedList<List<String>>();
		if (StringUtil.isEmpty(device.getPagecount())) {
			device.setPagecount(Constant.Excel.EXPORT_ROWS);
		}
		if (StringUtil.isEmpty(device.getPagenumber())) {
			device.setPagenumber("1");
		}
		device.setIsExport("true");
		PageModel<DeviceVO> pageModel = queryDevicelistPage(device);
		List<DeviceVO> list = pageModel.getQueryresult();
		DeviceVO deviceinfo = null;
		// long start = System.currentTimeMillis();
		for (int m = 0; m < list.size(); m++) {
			List<String> value = new LinkedList<String>();
			deviceinfo = list.get(m);
			switch (deviceinfo.getDevicetype()) {
			case "1":
				value.add("手表");
				break;
			case "2":
				value.add("智能学生证");
				break;
			case "3":
				value.add("考勤卡");
				break;
			case "8":
				value.add("13.56");
				break;
			case "9":
				value.add("2.4");
				break;
			default:
				value.add(null);
			}
			value.add(deviceinfo.getFactory());
			value.add(deviceinfo.getMdtid());
			value.add(deviceinfo.getTelephone());
			value.add(deviceinfo.getCardid());
			value.add(deviceinfo.getStudentname());
			value.add(deviceinfo.getClassname());
			value.add(deviceinfo.getSchoolname());
			value.add(deviceinfo.getTeachertel());
			value.add(deviceinfo.getParenttel());
			value.add(deviceinfo.getStarttime());
			value.add(deviceinfo.getEndtime());
			value.add(deviceinfo.getPaystatus());
			value.add(deviceinfo.getFee() != null ? deviceinfo.getFee().toString() : "");
			value.add(deviceinfo.getFee2() != null ? deviceinfo.getFee2().toString() : "");
			listValue.add(value);
		}
		return exportList(Constant.Excel.DEVICE_EXCEL, listParm, listValue);
	}

	/**
	 * <p>
	 * Title: recycleToReserve
	 * </p>
	 * <p>
	 * 功能描述:回收到储备量
	 * </p>
	 * 
	 * @param imei
	 * @return
	 */
	@Override
	@Transactional
	public String recycleToReserve(String imei, String province, String city, String town) {
		String[] imeiArr = imei.split("[|]");
		Map<String, Object> map = null;
		for (String imeiTemp : imeiArr) {
			// 判断是否为考勤卡
			if (imeiTemp.length() != 14 || (!imeiTemp.startsWith("8888") && !imei.startsWith("9999"))) {
				throw new RuntimeException("智能学生证不能进行区域储备量回收操作");
			}
			// 判断考勤卡是否是未激活设备，只有未激活设备才能回收
			map = new HashMap<String, Object>();
			map.put("imei", imeiTemp);
			// map.put("cardid", imeiTemp.substring(4));
			map.put("status", 1);
			PageQueryModel pqm = new PageQueryModel(1, 1, null, null);
			pqm.setQueryParam(map);
			PageGrid pageGrid = this.commonService.pageForObject("OpDeviceExtendSql.getInActivePage", pqm);
			if (pageGrid == null || pageGrid.getRows() == null || pageGrid.getRows().size() == 0) {
				throw new RuntimeException("设备" + imeiTemp + "状态不符，只有未激活设备才能回收");
			}

			// 添加device_reserve表
			DeviceReserve deviceReserve = new DeviceReserve();
			deviceReserve.setAddtime(new Date());
			deviceReserve.setCardid((String) pageGrid.getRows().get(0).get("cardid"));
			deviceReserve.setProvince(province);
			deviceReserve.setCity(city);
			deviceReserve.setTown(town);
			if (imeiTemp.startsWith("8888")) {
				deviceReserve.setDevicetype(1);
			} else if (imei.startsWith("9999")) {
				deviceReserve.setDevicetype(2);
			}
			deviceReserve.setStatus(0);
			deviceReserve.setUpdatetime(new Date());
			deviceReserveMapper.insertSelective(deviceReserve);

			// 删除devicelists表
			DevicelistExample devicelistExample = new DevicelistExample();
			devicelistExample.createCriteria().andMdtidEqualTo(imeiTemp);
			devicelistMapper.deleteByExample(devicelistExample);
		}
		return Constant.SUCCESS;
	}

	private void trimStudent(StudentModel student) {
		if (StringUtil.isNotBlank(student.getStudentName())) {
			student.setStudentName(student.getStudentName().replaceAll(" ", ""));
		}
		if (StringUtil.isNotBlank(student.getCardId())) {
			student.setCardId(student.getCardId().replaceAll(" ", ""));
		}
		if (StringUtil.isNotBlank(student.getHeadmasterTelephone())) {
			student.setHeadmasterTelephone(student.getHeadmasterTelephone().replaceAll(" ", ""));
		}
		if (StringUtil.isNotBlank(student.getPeopletel())) {
			student.setPeopletel(student.getPeopletel().replaceAll(" ", ""));
		}
		if (StringUtil.isNotBlank(student.getIsMainGuardian())) {
			student.setIsMainGuardian(student.getIsMainGuardian().replaceAll(" ", ""));
		}
		if (StringUtil.isNotBlank(student.getMainGuardianTelephone())) {
			student.setMainGuardianTelephone(student.getMainGuardianTelephone().replaceAll(" ", ""));
		}
	}

	private void addStdPeopleObject(Integer objectId, Integer peopleId, String familyStatus) {
		StdPeopleObjectExample stdPeopleObjectExample = new StdPeopleObjectExample();
		StdPeopleObject stdPeopleObject = new StdPeopleObject();
		if ("班主任".equals(familyStatus)) {
			stdPeopleObjectExample.createCriteria().andObjectidEqualTo(objectId).andFamilystatusEqualTo("班主任");
			List<StdPeopleObject> peopleObjectList = stdPeopleObjectMapper.selectByExample(stdPeopleObjectExample);
			if (CollectionUtils.isNotEmpty(peopleObjectList)) {
				if (!String.valueOf(peopleId).equals(String.valueOf(peopleObjectList.get(0).getPeopleid()))) {
					// 如果原班主任与当前班主任不一致时，则更新为新的班主任
					stdPeopleObjectMapper.deleteByPrimaryKey(peopleObjectList.get(0).getId());
					stdPeopleObject.setFamilystatus(familyStatus);
					stdPeopleObject.setIspush(true);
					stdPeopleObject.setTimeinterval(10);
					stdPeopleObject.setCreatetime(new Date());
					stdPeopleObject.setObjectid(objectId);
					stdPeopleObject.setPeopleid(peopleId);
					stdPeopleObjectMapper.insertSelective(stdPeopleObject);
					return;
				} else {
					return;
				}
			}
		}
		stdPeopleObjectExample.createCriteria().andPeopleidEqualTo(peopleId).andObjectidEqualTo(objectId);
		List<StdPeopleObject> peopleObjectList = stdPeopleObjectMapper.selectByExample(stdPeopleObjectExample);
		stdPeopleObject.setObjectid(objectId);
		stdPeopleObject.setPeopleid(peopleId);
		if (CollectionUtils.isEmpty(peopleObjectList)) {
			stdPeopleObject.setFamilystatus(familyStatus);
			stdPeopleObject.setIspush(true);
			stdPeopleObject.setTimeinterval(10);
			stdPeopleObject.setCreatetime(new Date());
			stdPeopleObjectMapper.insertSelective(stdPeopleObject);
		}
	}

	private Object addStdObjectInfo(String mdtid, String telephone, Integer peopleId, String schoolName,
			String studentName, String babyName, Integer jxtBabyId, String isMainGuardian) {
		// 查询该学生是否已存在，若存在，则修改，不存在，则新增
		StdObjectinfo objectInfo = getObjectInfoByJxtBabyIdAndStudentName(jxtBabyId, studentName);
		Schoolinfo school = getSchoolBySchoolName(schoolName);
		StdObjectinfo stdObjectinfo = new StdObjectinfo();
		if (mdtid != null) {
			stdObjectinfo.setMdtid(mdtid);
		}
		stdObjectinfo.setUpdatetime(new Date());
		if (telephone != null) {
			stdObjectinfo.setSimid(telephone);
		}
		stdObjectinfo.setSchoolid(school.getId());
		stdObjectinfo.setSchoolname(schoolName);
		stdObjectinfo.setStudentname(studentName);
		stdObjectinfo.setObjectname(babyName);
		stdObjectinfo.setJxtBabyid(jxtBabyId);
		stdObjectinfo.setHoldid(1);
		if (objectInfo == null) {
			// 如果不是主监护人，且该设备还没主监护人，则返回
			if (StringUtils.isNotBlank(isMainGuardian) && !"是".equals(isMainGuardian)) {
				return "请先为该设备添加管理员，再添加监护成员";
			}
			stdObjectinfo.setPeopleid(peopleId);
			stdObjectinfo.setCenterid(1);
			stdObjectinfo.setCreatetime(new Date());
			stdObjectinfo.setIsdeleted(false);
			stdObjectinfoMapper.insertSelective(stdObjectinfo);
		} else {
			if ("是".equals(isMainGuardian)) {
				stdObjectinfo.setPeopleid(peopleId);
			}
			stdObjectinfo.setObjectid(objectInfo.getObjectid());
			stdObjectinfoMapper.updateByPrimaryKeySelective(stdObjectinfo);
		}
		return stdObjectinfo.getObjectid();
	}

	private StdObjectinfo getObjectInfoByJxtBabyIdAndStudentName(Integer jxtBabyId, String studentName) {
		StdObjectinfoExample stdObjectinfoExample = new StdObjectinfoExample();
		stdObjectinfoExample.createCriteria().andIsdeletedEqualTo(false).andJxtBabyidEqualTo(jxtBabyId)
				.andStudentnameEqualTo(studentName);
		List<StdObjectinfo> objectInfoList = stdObjectinfoMapper.selectByExample(stdObjectinfoExample);
		if (CollectionUtils.isEmpty(objectInfoList)) {
			return null;
		} else {
			return objectInfoList.get(0);
		}
	}

	private List<StdObjectinfo> getObjectInfoByMdtid(String mdtid) {
		StdObjectinfoExample stdObjectinfoExample = new StdObjectinfoExample();
		stdObjectinfoExample.createCriteria().andIsdeletedEqualTo(false).andMdtidEqualTo(mdtid);
		List<StdObjectinfo> objectInfoList = stdObjectinfoMapper.selectByExample(stdObjectinfoExample);
		return objectInfoList;
	}

	private Schoolinfo getSchoolBySchoolName(String schoolName) {
		if (StringUtils.isNotBlank(schoolName)) {
			SchoolinfoExample schoolinfoExample = new SchoolinfoExample();
			schoolinfoExample.createCriteria().andSchoolnameEqualTo(schoolName);
			List<Schoolinfo> schoolinfoList = schoolinfoMapper.selectByExample(schoolinfoExample);
			if (CollectionUtils.isEmpty(schoolinfoList)) {
				return null;
			} else {
				return schoolinfoList.get(0);
			}
		}
		return null;
	}

	private void activateCardId(String cardId) {
		// 修改devicelist表，将状态置为已激活状态
		DevicelistExample devicelistExample = new DevicelistExample();
		devicelistExample.createCriteria().andIsinitEqualTo(false).andStatusEqualTo(0).andCardidEqualTo(cardId);
		Devicelist devicelist = new Devicelist();
		devicelist.setUpdatetime(new Date());
		devicelist.setIsinit(true);
		devicelist.setStatus(1);
		devicelistMapper.updateByExampleSelective(devicelist, devicelistExample);
	}

	private void addStdDeviceInfo(String mdtid, Integer objectId, Integer peopleId, String isMainGuardian) {
		// 查询当前数据是否已存在，若存在，则返回，反之，新增
		StdDeviceinfoExample stdDeviceinfoExample = new StdDeviceinfoExample();
		stdDeviceinfoExample.createCriteria().andMdtidEqualTo(mdtid).andIsdeletedEqualTo(0).andIsactiveEqualTo(true);
		List<StdDeviceinfo> deviceInfoList = stdDeviceinfoMapper.selectByExample(stdDeviceinfoExample);
		StdDeviceinfo stdDeviceInfo = new StdDeviceinfo();
		stdDeviceInfo.setUpdatetime(new Date());
		stdDeviceInfo.setObjectid(objectId);
		if (CollectionUtils.isEmpty(deviceInfoList)) {
			// 新增std_deviceinfo表
			stdDeviceInfo.setMdtcode(mdtid);
			stdDeviceInfo.setMdtid(mdtid);
			stdDeviceInfo.setCenterid(1);
			stdDeviceInfo.setDevicetype("3");
			stdDeviceInfo.setPeopleid(peopleId);
			stdDeviceInfo.setEndtime(DateUtil.formatStringToTime("2099-12-31 00:00:00", "yyyy-MM-dd HH:mm:ss"));
			stdDeviceInfo.setFee(new BigDecimal(0));
			stdDeviceInfo.setFee2(new BigDecimal(0));
			stdDeviceInfo.setFirewall(true);
			stdDeviceInfo.setHoldid(1);
			stdDeviceInfo.setIsactive(true);
			stdDeviceInfo.setIsdeleted(0);
			stdDeviceInfo.setIsshutdown(false);
			stdDeviceInfo.setStarttime(new Date());
			stdDeviceinfoMapper.insertSelective(stdDeviceInfo);
		} else {
			// 如果是主监护人，则修改peopleid为当前主监护人的id
			if (StringUtil.isNotBlank(isMainGuardian) && "是".equals(isMainGuardian)
					|| "0".equals(String.valueOf(deviceInfoList.get(0).getPeopleid()))) {
				stdDeviceInfo.setPeopleid(peopleId);
			}
			stdDeviceInfo.setDeviceid(deviceInfoList.get(0).getDeviceid());
			stdDeviceinfoMapper.updateByPrimaryKeySelective(stdDeviceInfo);
		}
	}

	private Object checkCardId(String cardId) {
		// 检查考勤卡，就算考勤卡已存在，也是合法的，可以继续执行
		Devicelist devicelist = getDeviceByCardId(cardId);
		if (devicelist == null) {
			return "考勤卡号不存在";
		}
		if ("1".equals(String.valueOf(devicelist.getStatus())) && devicelist.getIsinit() == true
				&& StringUtil.isNotBlank(devicelist.getSchoolname())) {
			return devicelist;
		} else if ("0".equals(String.valueOf(devicelist.getStatus())) && devicelist.getIsinit() == false
				&& StringUtil.isNotBlank(devicelist.getSchoolname())) {
			return devicelist;
		} else {
			return "考勤卡状态不符";
		}
	}

	private Devicelist getDeviceByCardId(String cardId) {
		DevicelistExample devicelistExample = new DevicelistExample();
		devicelistExample.createCriteria().andCardidEqualTo(cardId).andDevicetypeEqualTo(3);
		List<Devicelist> deviceList = devicelistMapper.selectByExample(devicelistExample);
		if (CollectionUtils.isEmpty(deviceList)) {
			return null;
		}
		return deviceList.get(0);
	}

	/**
	 * <p>
	 * Title: synJxtBaby
	 * </p>
	 * <p>
	 * 功能描述: 同步数据到家校通，解决随寻这边的异常数据
	 * </p>
	 * 
	 * @param mdtid
	 * @param headmasterTelephone
	 * @return
	 */
	@Override
	public String synJxtBaby(String mdtid) {
		if (StringUtil.isBlank(mdtid)) {
			return "设备号不能为空";
		}
		StdObjectinfoExample stdObjectinfoExample = new StdObjectinfoExample();
		stdObjectinfoExample.createCriteria().andMdtidEqualTo(mdtid).andIsdeletedEqualTo(false);
		List<StdObjectinfo> objectList = stdObjectinfoMapper.selectByExample(stdObjectinfoExample);
		if (CollectionUtils.isEmpty(objectList)) {
			return "该设备号没有关联学生";
		}
		Integer objectId = objectList.get(0).getObjectid();
		if (objectId == null) {
			return "学生数据异常";
		}
		StdPeopleObjectExample stdPeopleObjectExample = new StdPeopleObjectExample();
		stdPeopleObjectExample.createCriteria().andObjectidEqualTo(objectId).andFamilystatusEqualTo("班主任");
		List<StdPeopleObject> peopleObjectList = stdPeopleObjectMapper.selectByExample(stdPeopleObjectExample);
		if (CollectionUtils.isEmpty(peopleObjectList)) {
			return "该学生还未绑定班主任";
		}
		Integer headmasterId = peopleObjectList.get(0).getPeopleid();
		if (headmasterId == null) {
			return "班主任数据异常";
		}
		StdPeopleinfo headmasterInfo = stdPeopleinfoMapper.selectByPrimaryKey(headmasterId);
		if (headmasterInfo == null || StringUtil.isBlank(headmasterInfo.getPeopletel())) {
			return "班主任不存在或手机号为空";
		}
		String headmasterTelephone = headmasterInfo.getPeopletel();
		String token = "eyJhbGciOiJIUzI1NiJ9.eyJqdGkiOiIzMzc4MSIsImlhdCI6MTUwMzkwNjc1OSwic3ViIjoienpwIiwia"
				+ "XNzIjoiMTUyMDgyMDY4MDgiLCJhdWQiOiJndWFyZGlhbiJ9.SVcHo9cnVHq3GRHh76w-8xS02Rv0E24k1UToFRsAD6U";
		String param = String.format("teachertel=%s&objectid=%d&token=%s", headmasterTelephone, objectId, token);
		try {
			String url = String.format("%s%s", Constants.getApiUrl(), Constant.API.SYN_JXT_BABY);
			String res = HttpUtil.sendPost(url, param, false);
			if (StringUtil.isBlank(res)) {
				return "同步到家校通失败";
			}
			Result result = new ObjectMapper().readValue(res, Result.class);
			if (result == null) {
				return "同步数据到家校通失败";
			} else if (!"50006".equals(result.getCode())) {
				return result.getMsg();
			}
		} catch (IOException e) {
			return "同步家校通失败";
		}
		return null;
	}

	public String batchAddStudent(Workbook wb) throws Exception {
		if (wb == null) {
			return "excel内容为空";
		}
		String[] title = { "考勤卡号", "学生姓名", "班主任手机号", "用户手机号", "是否是主监护人", "主监护人手机号" };
		String res = ExcelUtil.checkExcel(wb, title, false);
		if (!Constant.TRUE.equals(res)) {
			return res;
		}
		// 获取excel数据
		ExcelUtil excelUtil = new ExcelUtil();
		Map<String, String> tableMap = new HashMap<>();
		tableMap.put("cardId", "考勤卡号");
		tableMap.put("studentName", "学生姓名");
		tableMap.put("headmasterTelephone", "班主任手机号");
		tableMap.put("peopletel", "用户手机号");
		tableMap.put("isMainGuardian", "是否是主监护人");
		tableMap.put("mainGuardianTelephone", "主监护人手机号");
		List<StudentModel> userList = excelUtil.getExcelValue(tableMap, wb, StudentModel.class);
		if (CollectionUtils.isEmpty(userList)) {
			return "excel内容为空";
		}
		List<String> recordList = new ArrayList<>();
		CountDownLatch latch = new java.util.concurrent.CountDownLatch(userList.size());
		ExecutorService executor = Executors.newFixedThreadPool(10);
		for (int i = 0; i < userList.size(); i++) {
			BatchImportCardThread thread = new BatchImportCardThread(latch, userList.get(i), i);
			executor.execute(thread);
		}

		latch.await();
		executor.shutdown();
		for (StudentModel student : userList) {
			if (student.getRecord() != null) {
				String errorMsg = String.format("行号:%s,列号:%s,错误原因:%s", student.getRecord().getRow(),
						student.getRecord().getCell(), student.getRecord().getRemark());
				recordList.add(errorMsg);
			}

			if (student.getObjectId() != null) {
				// 清缓存
				cacheService.flushGuardians(student.getObjectId());
				if (student.getMdtid() != null) {
					cacheService.refreshDeviceCache(student.getMdtid());
				}
				cacheService.flushBabys(parentService.getGuardiansByObjectId(student.getObjectId()));
				cacheService.flushFullBaby(student.getPeopleId(), student.getObjectId());
			}
		}
		if (recordList.size() > 0) {
			return String.format("存在以下错误：<br/>%s", StringUtils.join(recordList, "<br/>"));
		}
		return null;
	}

	@Override
	public void addStudent(StudentModel student, int index) {
		ExcelErrorRecord record = checkNull(student, index);
		if (record != null) {
			student.setRecord(record);
			return;
		}
		trimStudent(student);
		student.setBabyName(student.getStudentName());
		if (StringUtils.isBlank(student.getCardId())) {
			// 考勤卡为空时，学校就不能为空
			/*
			 * Integer schoolId = getSchoolIdBySchoolName(student, index); if
			 * (schoolId == null) { return; }
			 */
			addStudentByCardIdIsNull(student, index);
		} else {
			addStudentByCardIdNotNull(student, index);
		}
	}

	private boolean addStudentByCardIdNotNull(StudentModel student, int index) {
		ExcelErrorRecord record = new ExcelErrorRecord();
		Object checkCardId = checkCardId(student.getCardId());
		Devicelist cardDevice = null;
		if (checkCardId instanceof String) {
			record.setRow(String.valueOf(index + 1));
			record.setRemark(checkCardId.toString());
			record.setCell("考勤卡号");
			student.setRecord(record);
			return false;
		} else {
			cardDevice = (Devicelist) checkCardId;
		}
		// 判断当前学生以及主监护人是否已经绑定了一个有效的设备，若已经绑定，则返回，一个学生只能有一个有效的设备
		if (StringUtils.isBlank(student.getIsMainGuardian()) || "是".equals(student.getIsMainGuardian())) {
			Map<String, Object> map = new HashMap<>();
			map.put("peopletel", student.getPeopletel());
			List<DeviceInfo> deviceInfoList = divicedao.getDeviceListByParam(map);
			if (!CollectionUtils.isEmpty(deviceInfoList)) {
				for (DeviceInfo deviceInfo : deviceInfoList) {
					if (deviceInfo.getStudentname() != null
							&& deviceInfo.getStudentname().equals(student.getStudentName())
							&& StringUtils.isNotBlank(deviceInfo.getMdtid())
							&& !cardDevice.getMdtid().equals(deviceInfo.getMdtid())) {
						record.setRow(String.valueOf(index + 1));
						record.setRemark(String.format("该学生已经绑定了设备号为%s的设备", deviceInfo.getMdtid()));
						record.setCell("用户手机号");
						student.setRecord(record);
						return false;
					}
				}
			}
		}
		// 若该考勤卡已激活，则判断激活的学生是否是当前的学生，若不是，则返回
		if (cardDevice.getStatus() == 1 && cardDevice.getIsinit() == true) {
			List<StdObjectinfo> objectList = getObjectInfoByMdtid(cardDevice.getMdtid());
			if (!CollectionUtils.isEmpty(objectList)
					&& !student.getStudentName().equals(objectList.get(0).getStudentname())) {
				record.setRow(String.valueOf(index + 1));
				record.setRemark("考勤卡号已激活");
				record.setCell("考勤卡号");
				student.setRecord(record);
				return false;
			}
		}
		student.setMdtid(cardDevice.getMdtid());
		student.setSimid(cardDevice.getTelephone());
		if (!activeStudent(student, index, record)) {
			return false;
		}
		return true;
	}

	/**
	 * 已弃用
	 * 
	 * @param wb
	 * @return
	 */
	public Object bindwhitecardBatchtemp(HSSFWorkbook wb) {
		Map<String, String> tableMap = new HashMap<>();
		String[] labels = { "学生姓名", "家长手机号", "学生证mdtid", "考勤卡mdtid" };
		String[] key = { "studentname", "parenttel", "xszmdtid", "ckqmdtid" };
		for (int i = 0; i < key.length; i++) {
			tableMap.put(key[i], labels[i]);
		}
		ExcelUtil excelUtil = new ExcelUtil();
		// 将excel数据读取到对象里
		List<BindwhitecardBatchModel> bindwhitecardBatchModels = null;
		try {
			bindwhitecardBatchModels = excelUtil.getExcelValue(tableMap, wb, BindwhitecardBatchModel.class);
		} catch (Exception e) {
			logger.equals("读取数据错误，请确认Excel表和里面的数据是否有误" + e.getCause());
			// BasicResult<T> res = new BasicResult<T>();
			// res.setCode(AdminConstants.CODE_500);
			// res.setMsg("读取数据错误，请确认Excel表和里面的数据是否有误");
			// return res;
			return new Result(APICode.FAIL, "读取数据错误，请确认Excel表和里面的数据是否有误");
		}
		// 检查数据有效性，1，验证手机号，2，去除重复记录，3，去重
		StringBuffer sb = new StringBuffer();

		// 验证读取到的数据是否包含空值
		List<String> xszmdtidlist = new ArrayList<String>();
		List<String> kqkmdtidlist = new ArrayList<String>();
		// List<String> studentnamelist = new ArrayList<String>();
		List<String> parenttellist = new ArrayList<String>();

		List<String> xszmdtidexistlist = new ArrayList<String>();
		List<String> kqkmdtidxistlist = new ArrayList<String>();

		for (BindwhitecardBatchModel bindwhitecardBatchModel : bindwhitecardBatchModels) {
			// String studentname =
			// bindwhitecardBatchModel.getStudentname().replaceAll(" ", "");
			// String parenttel =
			// bindwhitecardBatchModel.getParenttel().replaceAll(" ", "");
			String xszmdtid = bindwhitecardBatchModel.getXszmdtid().replaceAll(" ", "");
			String kqkmdtid = bindwhitecardBatchModel.getCkqmdtid().replaceAll(" ", "");

			// if(StringUtils.isEmpty(studentname)){
			// sb.append("手机号"+parenttel+"对应的学生姓名为空；");
			// continue;
			// }
			// if(StringUtils.isEmpty(parenttel)){
			// sb.append("学生名为"+studentname+"的学生对应的家长手机号为空；");
			// continue;
			// }
			if (StringUtils.isEmpty(xszmdtid)) {
				// sb.append("学生名为"+studentname+"的学生对应的学生证mdtid为空；");
				continue;
			}
			if (StringUtils.isEmpty(kqkmdtid)) {
				// sb.append("学生名为"+studentname+"的学生对应的考勤卡mdtid为空；");
				continue;
			}
			// if(!StringUtils.isNumeric(parenttel)){
			// sb.append("学生名为"+studentname+"的学生的家长电话不合法；");
			// continue;
			// }
			if (!StringUtils.isNumeric(xszmdtid)) {
				// sb.append("学生名为"+studentname+"的学生的家长电话不合法；");
				continue;
			}
			xszmdtidlist.add(xszmdtid);
			kqkmdtidlist.add(kqkmdtid);
			// studentnamelist.add(studentname);
			// parenttellist.add(parenttel);
		}
		if (xszmdtidlist == null || xszmdtidlist.size() == 0) {
			return new Result(com.suixun.enums.APICode.HTTP_900.setCustomMsg("没有有效数据，请确认你的excel表数据"), null);
		}
		// 验证学生证是否存在，学生名字是否一致
		StdObjectinfoExample example = new StdObjectinfoExample();
		example.createCriteria().andMdtidIn(xszmdtidlist);
		List<StdObjectinfo> stdObjectinfos = stdObjectinfoMapper.selectByExample(example);
		if (stdObjectinfos == null || stdObjectinfos.size() == 0) {
			return new Result(com.suixun.enums.APICode.HTTP_900.setCustomMsg("根据学生证mdtid，找不到对应的学生"), null);
		}
		for (StdObjectinfo stdObjectinfo : stdObjectinfos) {
			if (!stdObjectinfo.getMdtid().startsWith("8888") && !stdObjectinfo.getMdtid().startsWith("9999")) {
				// int index = xszmdtidlist.indexOf(stdObjectinfo.getMdtid());
				// if(!studentnamelist.get(index).equals(stdObjectinfo.getStudentname())){
				// sb.append("学生名为"+studentnamelist.get(index)+"的学生与后台姓名不一致；");
				// continue;
				// }else {
				// xszmdtidexistlist.add(stdObjectinfo.getMdtid());
				// }
				xszmdtidexistlist.add(stdObjectinfo.getMdtid());
			}
		}

		int len = xszmdtidlist.size();
		for (int i = 0; i < len; i++) {
			if (!xszmdtidexistlist.contains(xszmdtidlist.get(i))) {
				sb.append("学生证号" + xszmdtidlist.get(i) + "找不到对应信息；");
				xszmdtidlist.remove(i);
				kqkmdtidlist.remove(i);
				// studentnamelist.remove(i);
				parenttellist.remove(i);
			}

		}
		// 验证将要绑定的考勤卡是否被占用
		// mdtid的需要在考勤卡前面加8888
		List<String> kqkmdtid8888list = new ArrayList<String>();
		for (String kqkmdtid : kqkmdtidlist) {
			// DevicelistExample devicelistExample = new DevicelistExample();
			// devicelistExample.createCriteria().andCardidEqualTo(kqkmdtid)
			if (kqkmdtid.length() != 10) {
				sb.append("考勤卡号为" + kqkmdtid + "的长度不是10位；");
			} else {
				kqkmdtid8888list.add("8888" + kqkmdtid);
			}
		}
		StdDeviceinfoExample stdDeviceinfoExample = new StdDeviceinfoExample();
		stdDeviceinfoExample.createCriteria().andMdtidIn(kqkmdtid8888list).andIsdeletedEqualTo(0)
				.andIsactiveEqualTo(true).andPeopleidNotEqualTo(0);
		List<StdDeviceinfo> stdDeviceinfos = stdDeviceinfoMapper.selectByExample(stdDeviceinfoExample);
		if (stdDeviceinfos != null && stdDeviceinfos.size() > 0) {
			// 已经被占用
			for (StdDeviceinfo stdDeviceinfo : stdDeviceinfos) {
				int i = kqkmdtid8888list.indexOf(stdDeviceinfo.getMdtid());
				sb.append("考勤卡" + kqkmdtidlist.get(i) + "已经被占用，不允许重复绑定；");
				xszmdtidlist.remove(i);
				kqkmdtidlist.remove(i);
				// studentnamelist.remove(i);
				parenttellist.remove(i);
				kqkmdtid8888list.remove(i);
			}
		}
		DevicelistExample devicelistExample = new DevicelistExample();
		devicelistExample.createCriteria().andCardidIn(kqkmdtidlist).andMdtidNotLike("8888%").andStatusEqualTo(1);
		List<Devicelist> devicelists = devicelistMapper.selectByExample(devicelistExample);
		if (devicelists != null && devicelists.size() > 0) {
			// 已经被占用
			for (Devicelist devicelist : devicelists) {
				int i = kqkmdtidlist.indexOf(devicelist.getCardid());
				sb.append("考勤卡" + kqkmdtidlist.get(i) + "已经被占用，不允许重复绑定；");
				xszmdtidlist.remove(i);
				kqkmdtidlist.remove(i);
				// studentnamelist.remove(i);
				parenttellist.remove(i);
				kqkmdtid8888list.remove(i);
			}
		}

		DevicelistExample devicelistExample2 = new DevicelistExample();
		devicelistExample2.createCriteria().andMdtidIn(kqkmdtid8888list);
		List<Devicelist> devicelist2 = devicelistMapper.selectByExample(devicelistExample2);
		if (devicelist2 == null && devicelist2.size() == 0) {
			return new Result(APICode.FAIL, "考勤卡均未入库");
		}
		List<String> rkkqkmdtidlist = new ArrayList<String>();
		for (Devicelist devicelist : devicelist2) {
			rkkqkmdtidlist.add(devicelist.getCardid());
		}

		for (String kqkmdtid : kqkmdtidlist) {
			int i = kqkmdtidlist.indexOf(kqkmdtid);
			if (!rkkqkmdtidlist.contains(kqkmdtid)) {
				sb.append("考勤卡" + kqkmdtid + "尚未入库；");
				xszmdtidlist.remove(i);
				kqkmdtidlist.remove(i);
				// studentnamelist.remove(i);
				parenttellist.remove(i);
				kqkmdtid8888list.remove(i);
			}
		}

		// 新的考勤卡 初始化
		Devicelist devicelist = new Devicelist();
		devicelist.setIsinit(true);
		devicelist.setStatus(1);
		devicelist.setUpdatetime(new Date());
		devicelistMapper.updateByExampleSelective(devicelist, devicelistExample2);

		// 学生证 devicelist里，学生证更新cardid为考勤卡号，
		DevicelistExample devicelistExample3 = new DevicelistExample();
		devicelistExample2.createCriteria().andMdtidIn(xszmdtidlist).andStatusEqualTo(1);
		List<Devicelist> devicelist3 = devicelistMapper.selectByExample(devicelistExample3);

		for (Devicelist devicelist33 : devicelist3) {
			int index = xszmdtidlist.indexOf(devicelist33.getMdtid());
			Devicelist devicelist4 = new Devicelist();
			devicelist4.setCardid(kqkmdtidlist.get(index));
			devicelist4.setId(devicelist33.getId());
			devicelistMapper.updateByPrimaryKeySelective(devicelist4);
			// mongodb cache
			// refreshDeviceCache(xszmdtidlist.get(index));
			// 清缓存
			// cacheService.flushBabys(objectService.getGuardians(fullObjectinfo.getMdtid()));
		}

		return new Result(APICode.SUCCESS, sb.toString());
	}

	@Override
	public Object getlostreportdevice(int pagenoint, int pagesizeint, int devicetype, int typeint) {

		// 1、设置分页信息：
		// 获取第1页，10条内容，默认查询总数count
		StdLostReportExample stdLostReportExample = new StdLostReportExample();
		com.suixun.entity.StdLostReportExample.Criteria criteria = stdLostReportExample.createCriteria();
		criteria.andStatusEqualTo(1);
		if (devicetype == 0) {
			// 所有
		} else {
			// 2所有已挂失学生证 3所有已挂失的考勤卡
			criteria.andDevicetypeEqualTo(devicetype);
		}
		if (typeint == 0) {
			// 所有
		} else if (typeint == 1) {
			// 已注销
			criteria.andLogoffsimstatusEqualTo(1);
		} else if (typeint == 2) {
			// 未注销
			criteria.andLogoffsimstatusIsNull();
		} else if (typeint == 3) {
			// 超过15天.且未注销
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(new Date());
			calendar.add(Calendar.DATE, -15);// 获取15天前的日期
			Date pDate = calendar.getTime();
			criteria.andLogoffsimstatusIsNull().andOptimeLessThan(pDate);
		}

		stdLostReportExample.setOrderByClause("optime asc");
		PageHelper.startPage(pagenoint, pagesizeint);
		// 紧跟着的第一个select方法会被分页
		List<StdLostReport> stdLostReports = stdLostReportMapper.selectByExample(stdLostReportExample);
		if (stdLostReports == null || stdLostReports.size() == 0) {
			return new Result(APICode.SUCCESS, null);
		}
		/*
		 * //查询对应的SIM是否注销 List<String> xszmdtidlist = new ArrayList<String>();
		 * List<String> xsztellist = new ArrayList<String>(); List<String>
		 * tellist = new ArrayList<String>();
		 * 
		 * for (StdLostReport stdLostReport : stdLostReports) {
		 * if(stdLostReport.getDevicetype() ==2){
		 * xszmdtidlist.add(stdLostReport.getMdtid());
		 * tellist.add(stdLostReport.getField1()); } } // DevicelistExample
		 * devicelistExample = new DevicelistExample(); //
		 * devicelistExample.createCriteria().andMdtidIn(xszmdtidlist); //
		 * List<Devicelist> devicelists
		 * =devicelistMapper.selectByExample(devicelistExample); //
		 * if(devicelists == null || devicelists.size() == 0){ //
		 * logger.error("数据错误，挂失设备在设备表里没有对应的数据 "); // return new
		 * Result(APICode.FAIL.setCustomMsg("数据错误，挂失设备在设备表里没有对应的数据 "), null); //
		 * } // for (Devicelist devicelist : devicelists) { //
		 * if(devicelist.getTelephone() !=null){ //
		 * xszmdtidlist.add(devicelist.getTelephone()); // } // }
		 * StdIotSimExample stdIotSimExample = new StdIotSimExample();
		 * stdIotSimExample.createCriteria().andStatusEqualTo((byte)-1).
		 * andPhoneIn(tellist);//andPhoneIn(xsztellist); List<StdIotSim>
		 * stdIotSims = stdIotSimMapper.selectByExample(stdIotSimExample);
		 * if(stdIotSims !=null && stdIotSims.size()> 0){ for (StdIotSim
		 * stdIotSim : stdIotSims) { for (StdLostReport stdLostReport :
		 * stdLostReports) {
		 * if(stdIotSim.getPhone().equals(stdLostReport.getField1())){
		 * stdLostReport.setLogoffsimstatus(-1); continue; } } } }
		 */

		PageInfo pageInfo = new PageInfo<>(stdLostReports);
		// com.suixun.model.PageGrid pageGrid = new com.suixun.model.PageGrid();
		// pageGrid.setTotal(pageInfo.getPages());
		// pageGrid.setPage(pageInfo.getPageNum());
		// pageGrid.setRecords((int)pageInfo.getTotal());
		// pageGrid.setRows(stdLostReports);
		return new Result(APICode.SUCCESS, pageInfo);
	}

	@Override
	public Result exportlostreportdevicelist(int flagint, DeviceManage deviceManage) {
		String tablesheetname = "挂失设备";
		StdLostReportExample stdLostReportExample = new StdLostReportExample();
		if (flagint == 1) {
			// 导出挂失日期超过15天的学生证,并且未注销的
			tablesheetname = "挂失超过15天的学生证手机号";
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(new Date());
			calendar.add(Calendar.DATE, -15);// 获取15天前的日期
			Date pDate = calendar.getTime();
			stdLostReportExample.createCriteria().andDevicetypeEqualTo(2).andStatusEqualTo(1).andLogoffsimstatusIsNull()
					.andOptimeLessThan(pDate);
		} else if (flagint == 2) {
			tablesheetname = "所有挂失设备";
			stdLostReportExample.createCriteria().andStatusEqualTo(1);
		} else if (flagint == 3) {
			tablesheetname = "挂失超过15天且未注销的考勤卡";
			Calendar calendar = Calendar.getInstance();
			calendar.setTime(new Date());
			calendar.add(Calendar.DATE, -15);// 获取15天前的日期
			Date pDate = calendar.getTime();
			stdLostReportExample.createCriteria().andDevicetypeEqualTo(3).andStatusEqualTo(1).andLogoffsimstatusIsNull()
					.andOptimeLessThan(pDate);
		} else if (flagint == 4) {
			// tablesheetname ="所有"
		}
		try {
			ArrayList<String> listParm = new ArrayList<String>();
			ArrayList<String> listExample = new ArrayList<String>();
			HSSFWorkbook workbook = null;
			String[] labels = { "设备手机号", "设备mdtid", "设备类型", "挂失日期" };
			for (String label : labels) {
				listParm.add(label);
			}
			List<List<String>> listValue = new LinkedList<List<String>>();
			List<StdLostReport> stdLostReports = stdLostReportMapper.selectByExample(stdLostReportExample);
			if (stdLostReports == null || stdLostReports.size() == 0) {
				return new Result(APICode.SUCCESS, null);
			}
			// 组装注销信息
			/*
			 * if(flagint == 1 || flagint ==2){ // stdLostReports =
			 * getLogoffLostDevicelist(stdLostReports);
			 * //如果只导出挂失超过15天且未注销的，需要把已注销过的移除 if(flagint == 1){ for
			 * (StdLostReport stdLostReport : stdLostReports) {
			 * if(stdLostReport.getLogoffsimstatus() == -1){
			 * stdLostReports.remove(stdLostReport); } } } }
			 */
			for (StdLostReport stdLostReport : stdLostReports) {
				List<String> item = new ArrayList<>();
				item.add(stdLostReport.getField1());
				item.add(stdLostReport.getMdtid());
				item.add(stdLostReport.getDevicetype() + "");
				SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				item.add(simpleDateFormat.format(stdLostReport.getOptime()));
				listValue.add(item);
			}
			// 创建新的Excel 工作簿

			workbook = deviceManage.exportDeviceList(tablesheetname, listParm, listExample, listValue);
			HttpServletResponse response = deviceManage.getResponse();
			response.setHeader("Content-disposition", "attachment;filename=exportbatchbindwhitecardTemplate.xls");
			workbook.write(deviceManage.getResponse().getOutputStream());
		} catch (Exception e) {
			// logger("TeacherController
			// exportbatchbindwhitecardTemplate:"+e.getMessage(),e);
			deviceManage.toRedirect(500);
		}
		return new Result(APICode.SUCCESS, null);
	}

	// 组装 挂失设备是否已注销信息
	/*
	 * public List<StdLostReport> getLogoffLostDevicelist(List<StdLostReport>
	 * stdLostReports){ //查询对应的SIM是否注销 List<String> tellist = new
	 * ArrayList<String>(); for (StdLostReport stdLostReport : stdLostReports) {
	 * if(stdLostReport.getDevicetype() ==2){
	 * tellist.add(stdLostReport.getField1()); } } StdIotSimExample
	 * stdIotSimExample = new StdIotSimExample();
	 * stdIotSimExample.createCriteria().andStatusEqualTo((byte)-1).andPhoneIn(
	 * tellist);//andPhoneIn(xsztellist); List<StdIotSim> stdIotSims =
	 * stdIotSimMapper.selectByExample(stdIotSimExample); if(stdIotSims !=null
	 * && stdIotSims.size()> 0){ for (StdIotSim stdIotSim : stdIotSims) { for
	 * (StdLostReport stdLostReport : stdLostReports) {
	 * if(stdIotSim.getPhone().equals(stdLostReport.getField1())){
	 * stdLostReport.setLogoffsimstatus(-1); continue; } } } } return
	 * stdLostReports; }
	 */

	@Override
	@Transactional
	public Result unbindwhitecardBatch(HSSFWorkbook wb) {
		Map<String, String> tableMap = new HashMap<>();
		String[] labels = { "学生姓名", "家长手机号", "考勤卡mdtid", "设备类型(2：智能学生证；31：13.56G考勤卡；32：2.4G考勤卡)" };
		String[] key = { "studentname", "parenttel", "ckqmdtid", "devicetype" };
		for (int i = 0; i < key.length; i++) {
			tableMap.put(key[i], labels[i]);
		}
		ExcelUtil excelUtil = new ExcelUtil();
		// 将excel数据读取到对象里
		List<BindwhitecardBatchModel> bindwhitecardBatchModels = null;
		try {
			bindwhitecardBatchModels = excelUtil.getExcelValue(tableMap, wb, BindwhitecardBatchModel.class);
		} catch (Exception e) {
			logger.equals("读取数据错误，请确认Excel表和里面的数据是否有误" + e.getCause());
			return new Result(APICode.FAIL, "读取数据错误，请确认Excel表和里面的数据是否有误");
		}
		StringBuffer sb = new StringBuffer();
		if (bindwhitecardBatchModels == null || bindwhitecardBatchModels.size() == 0) {
			return new Result(APICode.FAIL.setCustomMsg("没有读取到数据或者数据有误，请确认后再试"), null);
		}
		List<String> kqkmdtidlist = new ArrayList<>();
		List<String> normalkqkmdtidlist = new ArrayList<>();
		// 验证设备类型是否有效
		for (BindwhitecardBatchModel bindwhitecardBatchModel : bindwhitecardBatchModels) {
			String devicetype = bindwhitecardBatchModel.getDevicetype();
			if (devicetype == null || (!devicetype.equals("32") && !devicetype.equals("31"))) {
				sb.append(bindwhitecardBatchModel.getStudentname() + "的考勤卡类型无效；");
				continue;
			}
			if (devicetype.equals("2")) {
				sb.append(bindwhitecardBatchModel.getStudentname() + "的设备类型无效，暂时不支持批量解除学生证的绑定；");
				bindwhitecardBatchModels.remove(bindwhitecardBatchModel);
			} else if (devicetype.equals("31") || devicetype.equals("32")) {
				if (bindwhitecardBatchModel.getCkqmdtid().length() != 10) {
					sb.append(bindwhitecardBatchModel.getStudentname() + "的考勤卡号无效，请确认后再试；");
					bindwhitecardBatchModels.remove(bindwhitecardBatchModel);
				} else {
					if (devicetype.equals("31")) {
						bindwhitecardBatchModel.setCkqmdtid("8888" + bindwhitecardBatchModel.getCkqmdtid());
					}
					if (devicetype.equals("32")) {
						bindwhitecardBatchModel.setCkqmdtid("9999" + bindwhitecardBatchModel.getCkqmdtid());
					}
					kqkmdtidlist.add(bindwhitecardBatchModel.getCkqmdtid());
				}

			}
		}
		if (kqkmdtidlist.size() == 0) {
			return new Result(APICode.FAIL.setCustomMsg("没有有效数据"), null);
		}
		// 是否该学生只绑定了考勤卡，绑定了学生证的暂不支持
		StdDeviceinfoExample stdDeviceinfoExample = new StdDeviceinfoExample();
		stdDeviceinfoExample.createCriteria().andMdtidIn(kqkmdtidlist).andPeopleidNotEqualTo(0)
				.andObjectidNotEqualTo(0);
		List<StdDeviceinfo> stdDeviceinfos = stdDeviceinfoMapper.selectByExample(stdDeviceinfoExample);
		if (stdDeviceinfos == null || stdDeviceinfos.size() == 0) {
			return new Result(APICode.FAIL.setCustomMsg("不存在只绑定过考勤卡的学生，请确认后再试"), null);
		}
		// 只对这些只绑定了考勤卡的学生进行操作
		for (StdDeviceinfo stdDeviceinfo : stdDeviceinfos) {
			if (stdDeviceinfo.getObjectid() != 0) {
				normalkqkmdtidlist.add(stdDeviceinfo.getMdtid());
			} else {
				sb.append("考勤卡号为" + stdDeviceinfo.getMdtid() + "的设备没有绑定到学生");
				stdDeviceinfos.remove(stdDeviceinfo);
			}
		}
		int len = kqkmdtidlist.size();
		for (int i = 0; i < len; i++) {
			if (!normalkqkmdtidlist.contains(kqkmdtidlist.get(i))) {
				sb.append(bindwhitecardBatchModels.get(i).getStudentname() + "还绑定了学生证；当前暂不支持对已绑定学生证的学生进行解除考勤卡的操作；");
				kqkmdtidlist.remove(i);
				bindwhitecardBatchModels.remove(i);
			}
		}

		for (StdDeviceinfo stdDeviceinfo : stdDeviceinfos) {
			// 1，根据考勤卡号查询对应的学生
			// 4，删除随寻端对应的孩子的所有关联监护人关系
			// 3，删除随寻端对应的孩子信息 逻辑删除
			// 5，初始化deviceinfo里的objectid。
			// 6，初始化devicelist里的设备信息。

			// 4，删除随寻端对应的孩子的所有关联监护人关系
			StdPeopleObjectExample stdPeopleObjectExample = new StdPeopleObjectExample();

			stdPeopleObjectExample.createCriteria().andObjectidEqualTo(stdDeviceinfo.getObjectid());
			List<StdPeopleObject> stdPeopleObjects = stdPeopleObjectMapper.selectByExample(stdPeopleObjectExample);
			if (stdPeopleObjects != null && stdPeopleObjects.size() > 0) {
				// 清缓redis存
				String peopleids = "";
				for (StdPeopleObject stdPeopleObject : stdPeopleObjects) {
					peopleids += "," + stdPeopleObject.getPeopleid();
					cacheService.flushFullBaby(stdPeopleObject.getPeopleid(), stdPeopleObject.getObjectid());
				}
				cacheService.flushBabys(peopleids.substring(1));
				stdPeopleObjectMapper.deleteByExample(stdPeopleObjectExample);
			}
			// 3，删除随寻端对应的孩子信息 逻辑删除
			StdObjectinfo stdObjectinfo = new StdObjectinfo();
			stdObjectinfo.setObjectid(stdDeviceinfo.getObjectid());

			// stdObjectinfo.setObjectid(stdDeviceinfo.getObjectid());
			stdObjectinfo.setIsdeleted(true);
			stdObjectinfo.setUpdatetime(new Date());
			stdObjectinfoMapper.updateByPrimaryKeySelective(stdObjectinfo);// deleteByPrimaryKey(stdDeviceinfo.getObjectid());
			// 5，初始化deviceinfo里的objectid。
			StdDeviceinfo record = new StdDeviceinfo();
			record.setDeviceid(stdDeviceinfo.getDeviceid());
			record.setObjectid(0);
			record.setPeopleid(0);
			record.setUpdatetime(new Date());
			stdDeviceinfoMapper.updateByPrimaryKeySelective(record);
			// 6，初始化devicelist里的设备信息。
			DevicelistExample devicelistExample = new DevicelistExample();
			devicelistExample.createCriteria().andMdtidEqualTo(stdDeviceinfo.getMdtid());
			Devicelist devicelist = new Devicelist();
			devicelist.setIsinit(false);
			devicelist.setStatus(0);
			devicelist.setUpdatetime(new Date());
			devicelistMapper.updateByExampleSelective(devicelist, devicelistExample);

		}

		logger.error(sb.toString());
		return new Result(APICode.SUCCESS, sb.toString());
	}

	@Override
	public Result changewhitecardBatch(HSSFWorkbook wb) {
		Map<String, String> tableMap = new HashMap<>();
		String[] labels = { "学生姓名", "家长手机号", /* "原考勤卡号mdtid", */"新考勤卡号mdtid", "新设备类型(31：13.56G考勤卡；32：2.4G考勤卡)" };
		String[] key = { "studentname", "parenttel", /* "oldkqkmdtid", */"ckqmdtid", "devicetype" };
		for (int i = 0; i < key.length; i++) {
			tableMap.put(key[i], labels[i]);
		}
		ExcelUtil excelUtil = new ExcelUtil();
		// 将excel数据读取到对象里
		List<BindwhitecardBatchModel> bindwhitecardBatchModels = null;
		try {
			bindwhitecardBatchModels = excelUtil.getExcelValue(tableMap, wb, BindwhitecardBatchModel.class);
		} catch (Exception e) {
			logger.equals("读取数据错误，请确认Excel表和里面的数据是否有误" + e.getCause());
			return new Result(APICode.FAIL, "读取数据错误，请确认Excel表和里面的数据是否有误");
		}
		StringBuffer sb = new StringBuffer();
		if (bindwhitecardBatchModels == null || bindwhitecardBatchModels.size() == 0) {
			return new Result(APICode.FAIL.setCustomMsg("没有读取到数据或者数据有误，请确认后再试"), null);
		}

		List<String> kqkmdtidlist = new ArrayList<>();// 新考勤卡号集合，
		// List<String> oldkqkmdtidlist = new ArrayList<>();
		// List<String> normalkqkmdtidlist = new ArrayList<>();
		// 验证设备类型是否有效
		for (BindwhitecardBatchModel bindwhitecardBatchModel : bindwhitecardBatchModels) {
			String devicetype = bindwhitecardBatchModel.getDevicetype();
			// 学生证 不支持
			if (devicetype.equals("2")) {
				sb.append(bindwhitecardBatchModel.getStudentname() + "的设备类型无效，此功能不支持批量更换学生证；");
				bindwhitecardBatchModels.remove(bindwhitecardBatchModel);
			} else if (devicetype.equals("31") || devicetype.equals("32")) {
				// 考勤卡位数验证
				if (bindwhitecardBatchModel.getCkqmdtid().length() != 10) {
					sb.append(bindwhitecardBatchModel.getStudentname() + "的新考勤卡号无效，请确认后再试；");
					bindwhitecardBatchModels.remove(bindwhitecardBatchModel);
					continue;
				} else {
					if (devicetype.equals("31")) {
						bindwhitecardBatchModel.setCkqmdtid("8888" + bindwhitecardBatchModel.getCkqmdtid());
					}
					if (devicetype.equals("32")) {
						bindwhitecardBatchModel.setCkqmdtid("9999" + bindwhitecardBatchModel.getCkqmdtid());
					}
					kqkmdtidlist.add(bindwhitecardBatchModel.getCkqmdtid());
					// oldkqkmdtidlist.add(bindwhitecardBatchModel.getOldkqkmdtid());
				}

			}
		}
		// 新的考勤卡是否被占用
		DevicelistExample devicelistExample = new DevicelistExample();
		devicelistExample.createCriteria().andMdtidIn(kqkmdtidlist).andIsinitEqualTo(true).andStatusEqualTo(1);
		List<Devicelist> devicelists = devicelistMapper.selectByExample(devicelistExample);
		if (devicelists != null && devicelists.size() > 0) {
			for (Devicelist devicelist : devicelists) {
				if (devicelist.getMdtid().length() > 4) {
					sb.append("mdtid为" + devicelist.getMdtid().substring(4) + "的考勤卡已经被占用；");
				} else {
					sb.append("mdtid为" + devicelist.getMdtid() + "的考勤卡已经被占用；");
				}
				int index = kqkmdtidlist.indexOf(devicelist.getMdtid());
				kqkmdtidlist.remove(index);
				// oldkqkmdtidlist.remove(index);
				bindwhitecardBatchModels.remove(index);
			}
		}

		for (BindwhitecardBatchModel bindwhitecardBatchModel : bindwhitecardBatchModels) {
			// 根据读取到的学生信息，查询学生绑定的设备，分三种情况，一种是只绑定了考勤卡的，一种是只绑定了学生证的，一种是即绑定了学生证又绑定了考勤卡的
			int index = kqkmdtidlist.indexOf(bindwhitecardBatchModel.getParenttel());
			Map<String, String> m = new HashMap<String, String>();
			m.put("peopletel", bindwhitecardBatchModel.getParenttel());
			m.put("studentname", bindwhitecardBatchModel.getStudentname());
			List<Map<String, Object>> lst = commonService
					.selectList("OpDeviceExtendSql.getbabyinfobystudentnameandpeopletel", m);
			if (lst == null || lst.size() == 0) {
				sb.append("学生名为" + bindwhitecardBatchModel.getStudentname() + "家长手机号为"
						+ bindwhitecardBatchModel.getParenttel() + "的信息有误；");
				kqkmdtidlist.remove(index);
				// oldkqkmdtidlist.remove(index);
				bindwhitecardBatchModels.remove(bindwhitecardBatchModel);
				continue;
			}
			BeanUtil<ChangeWhiteCardModel> beanUtil = new BeanUtil<ChangeWhiteCardModel>();
			List<ChangeWhiteCardModel> changeWhiteCardModels = null;
			try {
				changeWhiteCardModels = beanUtil.ListMap2JavaBean(lst, ChangeWhiteCardModel.class);
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
				sb.append("学生名为" + bindwhitecardBatchModel.getStudentname() + "家长手机号为"
						+ bindwhitecardBatchModel.getParenttel() + "数据操作出错；");
			}

			// 是否绑定了学生证
			ChangeWhiteCardModel changeWhiteCardModel = changeWhiteCardModels.get(0);
			String devicetype = changeWhiteCardModel.getDevicetype();
			if (devicetype.equals(3)) {
				/**
				 * 只绑定了考勤卡 1，更新stdobjectinfo表中的mdtid为新的考勤卡号 2，原考勤卡复位 3，新考勤卡初始化
				 */
				// 1，更新stdobjectinfo表中的mdtid为新的考勤卡号
				StdObjectinfo stdObjectinfo = new StdObjectinfo();
				stdObjectinfo.setObjectid(changeWhiteCardModel.getObjectid());
				stdObjectinfo.setMdtid(bindwhitecardBatchModel.getCkqmdtid());
				stdObjectinfo.setUpdatetime(new Date());
				stdObjectinfoMapper.updateByPrimaryKeySelective(stdObjectinfo);
				// 2，原考勤卡复位
				DevicelistExample devicelistExample2 = new DevicelistExample();
				devicelistExample2.createCriteria().andMdtidEqualTo(changeWhiteCardModel.getMdtid());
				Devicelist devicelist = new Devicelist();
				devicelist.setIsinit(false);
				devicelist.setStatus(0);
				devicelist.setUpdatetime(new Date());
				devicelistMapper.updateByExampleSelective(devicelist, devicelistExample2);
				// 3，新考勤卡初始化
				DevicelistExample devicelistExample3 = new DevicelistExample();
				devicelistExample3.createCriteria().andMdtidEqualTo(kqkmdtidlist.get(index));
				Devicelist devicelist3 = new Devicelist();
				devicelist3.setIsinit(true);
				devicelist3.setStatus(1);
				devicelist3.setUpdatetime(new Date());
				devicelistMapper.updateByExampleSelective(devicelist3, devicelistExample3);
			} else if (devicetype.equals(2)) {
				// 绑定了学生证
				/**
				 * 1，根据stdobjectinfo表中的学生证mdtid到devicelist中查询设备信息，
				 * 2，更新学生证设备信息中的cardid为新的考勤卡号 3，原考勤卡复位 4，新考勤卡初始化
				 */
				// 2，更新学生证设备信息Devicelist中的cardid为新的考勤卡号
				DevicelistExample devicelistExample4 = new DevicelistExample();
				devicelistExample4.createCriteria().andMdtidEqualTo(changeWhiteCardModel.getMdtid());
				Devicelist devicelist2 = new Devicelist();
				devicelist2.setCardid(kqkmdtidlist.get(index));
				devicelist2.setUpdatetime(new Date());
				devicelistMapper.updateByExample(devicelist2, devicelistExample4);
				// StdDeviceinfo stdDeviceinfo = new StdDeviceinfo();
				// stdDeviceinfo.setDeviceid(changeWhiteCardModel.getDeviceid());
				// stdDeviceinfo.setcar(Integer.parseInt(kqkmdtidlist.get(index)));
				// stdDeviceinfoMapper.updateByPrimaryKeySelective(stdDeviceinfo);
				// 2，原考勤卡复位
				DevicelistExample devicelistExample2 = new DevicelistExample();
				devicelistExample2.createCriteria().andMdtidLike(changeWhiteCardModel.getCardid());
				Devicelist devicelist = new Devicelist();
				devicelist.setIsinit(false);
				devicelist.setStatus(0);
				devicelist.setCardid(changeWhiteCardModel.getCardid());
				devicelistMapper.updateByExampleSelective(devicelist, devicelistExample2);
				// 3，新考勤卡初始化
				DevicelistExample devicelistExample3 = new DevicelistExample();
				devicelistExample3.createCriteria().andMdtidEqualTo(kqkmdtidlist.get(index));
				Devicelist devicelist3 = new Devicelist();
				devicelist3.setIsinit(true);
				devicelist3.setStatus(1);
				devicelistMapper.updateByExampleSelective(devicelist3, devicelistExample3);
			}

		}

		logger.error(sb.toString());
		return new Result(APICode.SUCCESS, sb.toString());
	}

	/**
	 * 
	 * <p>
	 * Title: addStudentByCardIdIsNull
	 * </p>
	 * <p>
	 * 功能描述:添加没有考勤卡的学生
	 * </p>
	 * 
	 * @param student
	 * @param index
	 * @return
	 */
	private boolean addStudentByCardIdIsNull(StudentModel student, int index) {
		ExcelErrorRecord record = new ExcelErrorRecord();
		if (!activeStudent(student, index, record)) {
			return false;
		}
		;
		return true;
	}

	private boolean activeStudent(StudentModel student, int index, ExcelErrorRecord record) {
		// 判断是否是主监护人
		if (StringUtils.isBlank(student.getIsMainGuardian()) || "是".equals(student.getIsMainGuardian())) {
			// 判断家长手机号是否已存在,若不存在，则添加账号并添加学生关系，反之，则继续往下
			if (StringUtils.isBlank(student.getMainGuardianTelephone())) {
				// 注册账号
				Integer peopleId = registerPeopleAccount(student, index, record);
				if (peopleId == null) {
					return false;
				}
				student.setMainGuardianTelephone(student.getPeopletel());
				// 同步学生到家校通
				Integer babyId = synStudentToJxt(student, index, record);
				if (babyId == null) {
					return false;
				}
				// 新增学生
				Integer objectId = addObjectInfo(student, index, record, peopleId, babyId, student.getMdtid(),
						student.getSimid());
				if (objectId == null) {
					return false;
				}
				// 添加家长和学生的关联关系
				addStdPeopleObject(objectId, peopleId, "家长");
				if (StringUtils.isNotBlank(student.getCardId())) {
					// 激活考勤卡
					activateCardId(student.getCardId());
					addStdDeviceInfo(student.getMdtid(), objectId, peopleId, student.getIsMainGuardian());
				}
				// 添加班主任
				Integer headmasterId = registerHeadmasterAccount(student, index, record);
				if (headmasterId == null) {
					return false;
				}
				// 添加班主任与学生的关联关系
				addStdPeopleObject(objectId, headmasterId, "班主任");
				// 这样做是为了在线程外刷新缓存
				student.setObjectId(objectId);
				student.setPeopleId(peopleId);
			} else if ("是".equals(student.getIsMainGuardian())
					&& StringUtils.isNotBlank(student.getMainGuardianTelephone())) {
				// 如果主监护人手机号不为空，则1.判断主监护人是否存在，2.在当前主监护人下找到是否确实是有绑定该学生
				Integer objectId = checkMainGuardianTelephoneIsLegal(student, index, record);
				if (objectId == null) {
					return false;
				}
				if (!checkGuardianIsFull(student, index, record, objectId)) {
					return false;
				}
				Integer peopleId = registerPeopleAccount(student, index, record);
				if (peopleId == null) {
					return false;
				}
				Integer babyId = synStudentToJxt(student, index, record);
				if (babyId == null) {
					return false;
				}
				objectId = addObjectInfo(student, index, record, peopleId, babyId, student.getMdtid(),
						student.getSimid());
				if (objectId == null) {
					return false;
				}
				// 添加家长和学生的关联关系
				addStdPeopleObject(objectId, peopleId, "家长");
				if (StringUtils.isNotBlank(student.getCardId())) {
					// 激活考勤卡
					activateCardId(student.getCardId());
					addStdDeviceInfo(student.getMdtid(), objectId, peopleId, student.getIsMainGuardian());
				}
				// 添加班主任
				Integer headmasterId = registerHeadmasterAccount(student, index, record);
				if (headmasterId == null) {
					return false;
				}
				// 添加班主任与学生的关联关系
				addStdPeopleObject(objectId, headmasterId, "班主任");
				// 同步主监护人到家校通
				if (!changeMainGuardianToJxt(student, index, record, babyId)) {
					return false;
				}
				// 这样做是为了在线程外刷新缓存
				student.setObjectId(objectId);
				student.setPeopleId(peopleId);
			} else {
				record.setRow(String.valueOf(index + 1));
				record.setCell("是否是主监护人");
				record.setRemark("需要更换主监护人，是否是主监护人一栏不能为空");
				student.setRecord(record);
				return false;
			}
		} else if ("否".equals(student.getIsMainGuardian())) {
			// 如果是普通监护人，则主监护人手机号不能为空
			if (StringUtils.isBlank(student.getMainGuardianTelephone())) {
				record.setRow(String.valueOf(index + 1));
				record.setCell("主监护人手机号");
				record.setRemark("该主监护人手机号不能为空");
				student.setRecord(record);
				return false;
			}
			Integer objectId = checkMainGuardianTelephoneIsLegal(student, index, record);
			if (objectId == null) {
				return false;
			}
			if (!checkGuardianIsFull(student, index, record, objectId)) {
				return false;
			}
			Integer peopleId = registerPeopleAccount(student, index, record);
			if (peopleId == null) {
				return false;
			}
			// 添加家长和学生的关联关系
			addStdPeopleObject(objectId, peopleId, "家长");
			// 这样做是为了在线程外刷新缓存
			student.setObjectId(objectId);
			student.setPeopleId(peopleId);
		} else {
			record.setRow(String.valueOf(index + 1));
			record.setCell("是否是主监护人");
			record.setRemark("只能在是/否中选择一个");
			student.setRecord(record);
			return false;
		}
		return true;
	}

	private boolean changeMainGuardianToJxt(StudentModel student, int index, ExcelErrorRecord record, Integer babyId) {
		// 同步主监护人到家校通
		JxtResult jxtResult = jxtService.modifyBabyParentMobile(student.getMainGuardianTelephone(),
				student.getPeopletel(), babyId);
		if (jxtResult == null) {
			record.setRow(String.valueOf(index + 1));
			record.setRemark("同步主监护人到家校通失败");
			record.setCell("主监护人手机号");
			student.setRecord(record);
			return false;
		}
		if (!"操作成功".equals(String.valueOf(jxtResult.getMsg()))) {
			record.setRow(String.valueOf(index + 1));
			record.setRemark("同步主监护人到家校通失败:" + jxtResult.getMsg());
			record.setCell("主监护人手机号");
			student.setRecord(record);
			return false;
		}
		return true;
	}

	private Integer addObjectInfo(StudentModel student, int index, ExcelErrorRecord record, Integer peopleId,
			Integer babyId, String mdtid, String simId) {
		Object objectResult = addStdObjectInfo(mdtid, simId, peopleId, student.getSchoolName(),
				student.getStudentName(), student.getBabyName(), babyId, student.getIsMainGuardian());
		if (objectResult != null && objectResult instanceof String) {
			record.setRow(String.valueOf(index + 1));
			record.setRemark(objectResult.toString());
			record.setCell("是否是主监护人");
			student.setRecord(record);
			return null;
		}
		return (Integer) objectResult;
	}

	private boolean checkGuardianIsFull(StudentModel student, int index, ExcelErrorRecord record, Integer objectId) {
		List<StdPeopleinfo> peopleList = divicedao.getPeopleListByObjectId(objectId);
		// 查询该设备下是否已绑定了超过7个监护成员
		if (CollectionUtils.isNotEmpty(peopleList) && peopleList.size() > 6) {
			record.setRow(String.valueOf(index + 1));
			record.setCell("学生姓名");
			record.setRemark("该学生下监护成员已满");
			student.setRecord(record);
			return false;
		}
		return true;
	}

	private Integer checkMainGuardianTelephoneIsLegal(StudentModel student, int index, ExcelErrorRecord record) {
		StdPeopleinfo mainGuardian = getPeopleInfoBytelephone(student.getMainGuardianTelephone());
		if (mainGuardian == null) {
			record.setRow(String.valueOf(index + 1));
			record.setCell("主监护人手机号");
			record.setRemark("该主监护人不存在");
			student.setRecord(record);
			return null;
		}
		StdObjectinfoExample stdObjectinfoExample = new StdObjectinfoExample();
		stdObjectinfoExample.createCriteria().andIsdeletedEqualTo(false).andPeopleidEqualTo(mainGuardian.getPeopleid())
				.andStudentnameEqualTo(student.getStudentName());
		List<StdObjectinfo> objectList = stdObjectinfoMapper.selectByExample(stdObjectinfoExample);
		if (CollectionUtils.isEmpty(objectList)) {
			record.setRow(String.valueOf(index + 1));
			record.setCell("主监护人手机号");
			record.setRemark("该主监护人没有绑定该学生,请核实姓名是否有误");
			student.setRecord(record);
			return null;
		}
		return objectList.get(0).getObjectid();
	}

	private Integer synStudentToJxt(StudentModel student, int index, ExcelErrorRecord record) {
		JxtResult jxtResult = jxtService.addBabyInfo(student.getHeadmasterTelephone(),
				student.getMainGuardianTelephone(), student.getStudentName());
		if (jxtResult == null) {
			record.setRow(String.valueOf(index + 1));
			record.setRemark("家校通同步失败");
			record.setCell("");
			student.setRecord(record);
			return null;
		}
		if (!"1".equals(String.valueOf(jxtResult.getCode()))) {
			record.setRow(String.valueOf(index + 1));
			record.setCell("");
			record.setRemark(jxtResult.getMsg());
			student.setRecord(record);
			return null;
		}
		String schoolName = jxtResult.getData().getSchool().getSchoolname();
		if (StringUtils.isBlank(schoolName)) {
			record.setRow(String.valueOf(index + 1));
			record.setRemark("家校通学校名称为空");
			record.setCell("班主任手机号");
			student.setRecord(record);
			return null;
		}
		student.setSchoolName(jxtResult.getData().getSchool().getSchoolname());
		return jxtResult.getData().getStudentId();
	}

	private Integer registerHeadmasterAccount(StudentModel student, int index, ExcelErrorRecord record) {
		Object result = parentService.registerAccount(student.getHeadmasterTelephone());
		if (result instanceof String) {
			record.setRow(String.valueOf(index + 1));
			record.setRemark(result.toString());
			record.setCell("班主任手机号");
			student.setRecord(record);
			return null;
		} else {
			return (Integer) result;
		}
	}

	private Integer registerPeopleAccount(StudentModel student, int index, ExcelErrorRecord record) {
		Integer peopleId = null;
		Object result = parentService.registerAccount(student.getPeopletel());
		if (result instanceof String) {
			record.setRow(String.valueOf(index + 1));
			record.setRemark(result.toString());
			record.setCell("用户手机号");
			student.setRecord(record);
			return null;
		} else {
			peopleId = (Integer) result;
			return peopleId;
		}
	}

	private StdPeopleinfo getPeopleInfoBytelephone(String telephone) {
		StdPeopleinfoExample stdPeopleinfoExample = new StdPeopleinfoExample();
		stdPeopleinfoExample.createCriteria().andPeopletelEqualTo(telephone).andIsdeletedEqualTo(false);
		List<StdPeopleinfo> peopleList = stdPeopleinfoMapper.selectByExample(stdPeopleinfoExample);
		if (CollectionUtils.isEmpty(peopleList)) {
			return null;
		} else {
			return peopleList.get(0);
		}
	}

	private ExcelErrorRecord checkNull(StudentModel student, int index) {
		ExcelErrorRecord record = new ExcelErrorRecord();
		if (StringUtils.isBlank(student.getHeadmasterTelephone())) {
			record.setRow(String.valueOf(index + 1));
			record.setRemark("班主任手机号为空");
			record.setCell("班主任手机号");
			student.setRecord(record);
			return record;
		}
		if (StringUtils.isBlank(student.getPeopletel())) {
			record.setRow(String.valueOf(index + 1));
			record.setRemark("用户手机号为空");
			record.setCell("用户手机号");
			student.setRecord(record);
			return record;
		}
		if (StringUtils.isBlank(student.getStudentName())) {
			record.setRow(String.valueOf(index + 1));
			record.setRemark("学生姓名为空");
			record.setCell("学生姓名");
			student.setRecord(record);
			return record;
		}
		return null;
	}

	@Override
	public List<DeviceVO> getDeviceListByPeopletel(String peopletel) {
		if (StringUtils.isBlank(peopletel) || !peopletel.matches("[1][0-9]{10}")) {
			return null;
		}
		Map<String, Object> map = new HashMap<>();
		map.put("peopletel", peopletel);
		List<DeviceInfo> deviceInfoList = divicedao.getDeviceListByParam(map);
		if (CollectionUtils.isEmpty(deviceInfoList)) {
			return null;
		}
		List<DeviceVO> deviceVoList = new ArrayList<>();
		List<DeviceVO> deviceList = null;
		ParamForm param = null;
		DeviceVO deviceVo = null;
		JxtResult jxtResult = null;
		for (DeviceInfo device : deviceInfoList) {
			if (StringUtils.isBlank(device.getMdtid())) {
				continue;
			}
			deviceVo = new DeviceVO();
			if (device.getJxtBabyId() != null) {
				jxtResult = jxtService.getStudentInfo(device.getJxtBabyId());
				if (jxtResult != null) {
					JxtStudent student = jxtResult.getData();
					if (student != null) {
						if (student.getSchool() != null) {
							deviceVo.setSchoolname(student.getSchool().getSchoolname());
						}
						deviceVo.setClassname(student.getClassName());
						deviceVo.setStudentname(student.getStudentName());
					}
				}
			}
			param = new ParamForm();
			param.setImei(device.getMdtid());
			deviceList = queryDevice(param);
			if (!CollectionUtils.isEmpty(deviceList)) {
				deviceVo.setPaymoney(deviceList.get(0).getPaymoney());
				deviceVo.setPaytime(deviceList.get(0).getPaytime());
				deviceVo.setPaystatus(deviceList.get(0).getPaystatus());
				deviceVo.setFee(deviceList.get(0).getFee());
				deviceVo.setFee2(deviceList.get(0).getFee2());
				deviceVo.setMdtid(deviceList.get(0).getMdtid());
				deviceVo.setTelephone(deviceList.get(0).getTelephone());
				deviceVo.setCardid(deviceList.get(0).getCardid());
				deviceVo.setDevicetype(deviceList.get(0).getDevicetype());
				deviceVo.setEndtime(deviceList.get(0).getEndtime());
				deviceVo.setStarttime(deviceList.get(0).getStarttime());
				deviceVo.setDevicetypename(deviceList.get(0).getDevicetypename());
				deviceVoList.add(deviceVo);
			}
		}
		return deviceVoList;
	}

	@Override
	public Integer getFirewallByMdtid(String mdtid) {
		if (StringUtils.isBlank(mdtid)) {
			return null;
		}
		StdDeviceinfoExample stdDeviceinfoExample = new StdDeviceinfoExample();
		stdDeviceinfoExample.createCriteria().andMdtidEqualTo(mdtid).andIsdeletedEqualTo(0);
		List<StdDeviceinfo> deviceInfoList = stdDeviceinfoMapper.selectByExample(stdDeviceinfoExample);
		if (CollectionUtils.isEmpty(deviceInfoList)) {
			return null;
		}
		boolean isOpen = deviceInfoList.get(0).getFirewall();
		if (isOpen) {
			return 1;
		} else {
			return -1;
		}
	}

	@Override
	public String batchChangeCard(Workbook wb) throws Exception {

		return null;
	}

	@Override
	public Object bindwhitecardBatch(HSSFWorkbook wb) {
		Map<String, String> tableMap = new HashMap<>();
		String[] labels = { "学生姓名", "家长手机号", "学生证mdtid", "考勤卡mdtid" };
		String[] key = { "studentname", "parenttel", "xszmdtid", "ckqmdtid" };
		for (int i = 0; i < key.length; i++) {
			tableMap.put(key[i], labels[i]);
		}
		ExcelUtil excelUtil = new ExcelUtil();
		// 将excel数据读取到对象里
		List<BindwhitecardBatchModel> bindwhitecardBatchModels = null;
		try {
			bindwhitecardBatchModels = excelUtil.getExcelValue(tableMap, wb, BindwhitecardBatchModel.class);
		} catch (Exception e) {
			logger.equals("读取数据错误，请确认Excel表和里面的数据是否有误" + e.getCause());
			return new Result(APICode.FAIL, "读取数据错误，请确认Excel表和里面的数据是否有误");
		}
		// 检查数据有效性，1，验证手机号，2，去除重复记录，3，去重
		StringBuffer sb = new StringBuffer();
		int len = bindwhitecardBatchModels.size();
		for (int i = 0; i < len; i++) {
			BindwhitecardBatchModel bindwhitecardBatchModel = bindwhitecardBatchModels.get(i);
			String xszmdtid = bindwhitecardBatchModel.getXszmdtid().replaceAll(" ", "");
			String ckqmdtid = bindwhitecardBatchModel.getCkqmdtid().replaceAll(" ", "");
			// xszmdtid =xszmdtid.substring(0, xszmdtid.length());
			// 验证读取的的数据的有效性
			if (xszmdtid.length() == 15) {
				xszmdtid = xszmdtid.substring(0, xszmdtid.length() - 1);
			}
			if (StringUtil.isEmpty(xszmdtid) || xszmdtid.length() < 14) {
				sb.append("第" + (i + 1) + "行的学生证号" + xszmdtid + "无效；");
				continue;
			}
			if (StringUtil.isEmpty(ckqmdtid) || ckqmdtid.length() != 10) {
				sb.append("第" + (i + 1) + "行的考勤卡号" + ckqmdtid + "无效；");
				continue;
			}
			// 考勤卡号是否入库或者已经被占用
			DevicelistExample devicelistExample = new DevicelistExample();
			devicelistExample.createCriteria().andCardidEqualTo(ckqmdtid).andIsinitEqualTo(false).andStatusEqualTo(0);
			List<Devicelist> cqkdevicelists = devicelistMapper.selectByExample(devicelistExample);
			if (cqkdevicelists == null || cqkdevicelists.size() == 0) {
				sb.append("第" + (i + 1) + "行的考勤卡" + ckqmdtid + "未入库或者已经被占用；");
				continue;
			}
			// ckqmdtid = cqkdevicelists.get(0).getMdtid();

			// 是否绑定了学生证，
			DevicelistExample devicelistExample2 = new DevicelistExample();
			devicelistExample2.createCriteria().andMdtidEqualTo(xszmdtid).andIsinitEqualTo(true).andStatusEqualTo(1);
			List<Devicelist> xszdevicelists2 = devicelistMapper.selectByExample(devicelistExample2);
			if (xszdevicelists2 == null || xszdevicelists2.size() == 0) {
				sb.append("第" + (i + 1) + "行的学生证" + xszmdtid + "不是有效使用中的设备；");
				continue;
			}
			// 已经绑定了学生证，是否绑定了考勤卡
			String existcardid = xszdevicelists2.get(0).getCardid();
			if (existcardid != null) {
				existcardid = existcardid.replaceAll(" ", "");
			}
			if (!StringUtil.isEmpty(existcardid)) {
				DevicelistExample devicelistExample3 = new DevicelistExample();
				List<String> existcqkmdtids = new ArrayList<>();
				existcqkmdtids.add("8888" + existcardid);
				existcqkmdtids.add("9999" + existcardid);
				devicelistExample3.createCriteria().andMdtidIn(existcqkmdtids).andIsinitEqualTo(true)
						.andStatusEqualTo(1);
				List<Devicelist> devicelistsexistcqks = devicelistMapper.selectByExample(devicelistExample3);
				if (devicelistsexistcqks != null && devicelistsexistcqks.size() > 0) {
					sb.append("第" + (i + 1) + "行的学生证" + xszmdtid + "对应的学生已经绑定过考勤卡了，请勿使用此接口执行；");
					continue;
				}

			}
			// 将考勤卡号写到学生证的cardid里
			Devicelist devicelist = new Devicelist();
			devicelist.setId(xszdevicelists2.get(0).getId());
			devicelist.setCardid(ckqmdtid);
			devicelist.setUpdatetime(new Date());
			devicelistMapper.updateByPrimaryKeySelective(devicelist);

			// 考勤卡在devicelist里初始化
			DevicelistExample devicelistExample3 = new DevicelistExample();
			devicelistExample3.createCriteria().andCardidEqualTo(ckqmdtid).andDevicetypeEqualTo(3)
					.andIsinitEqualTo(false);
			Devicelist devicelistcqk = new Devicelist();
			devicelistcqk.setIsinit(true);
			devicelistcqk.setStatus(1);
			devicelistcqk.setCardid("");
			devicelistcqk.setUpdatetime(new Date());
			devicelistMapper.updateByExampleSelective(devicelistcqk, devicelistExample3);
			// devicelistMapper.updateByPrimaryKeySelective(devicelistcqk);

		}

		return new Result(APICode.SUCCESS, sb.toString());
	}

	@Transactional
	@Override
	public Result logoffafterlost(String lostreportids/* ,String mdtids */) {
		List<String> list = Arrays.asList(lostreportids.split(","));
		// List<String> mdtidslist = Arrays.asList(mdtids.split(","));
		List<Integer> lostreportidslist = new ArrayList<>();
		// if(list.size() != mdtidslist.size()){
		// return new Result(APICode.FAIL.setCustomMsg("请选择你要挂失的有效设备"), null);
		// }
		for (String id : list) {
			Integer idInt = Integer.parseInt(id);
			lostreportidslist.add(idInt);
		}
		if (lostreportidslist == null || lostreportidslist.size() == 0) {
			return new Result(APICode.FAIL.setCustomMsg("请选择你要挂失的有效设备"), null);
		}
		StdLostReport stdLostReport = new StdLostReport();
		stdLostReport.setLogoffsimstatus(-1);
		StdLostReportExample stdLostReportExample = new StdLostReportExample();
		stdLostReportExample.createCriteria().andStatusEqualTo(1).andIdIn(lostreportidslist);

		List<StdLostReport> stdLostReports = stdLostReportMapper.selectByExample(stdLostReportExample);
		List<String> telephones = new ArrayList<>();
		for (StdLostReport stdLostReport2 : stdLostReports) {
			if (stdLostReport2.getDevicetype() == 2) {
				// 学生证注销sim，需要更新std_ioc_sim
				telephones.add(stdLostReport2.getField1());
			}
		}

		if (telephones.size() > 0) {
			StdIotSim stdIotSim = new StdIotSim();
			Byte status = new Byte((byte) -1);
			stdIotSim.setStatus(status);
			StdIotSimExample stdIotSimExample = new StdIotSimExample();
			stdIotSimExample.createCriteria().andPhoneIn(telephones);
			// stdIotSimExample.createCriteria().andPhoneEqualTo(telephones.get(0));
			stdIotSimMapper.updateByExampleSelective(stdIotSim, stdIotSimExample);

		}

		// 不能放在 前面，因为stdLostReportExample是共用的，当这个先执行，
		stdLostReportMapper.updateByExampleSelective(stdLostReport, stdLostReportExample);

		return new Result(APICode.SUCCESS, null);
	}

	@Override
	public Result getlostinfobymdtid(String mdtid) {
		List<String> mdtidlist = new ArrayList<>();
		mdtidlist.add(mdtid);
		mdtidlist.add("8888" + mdtid);
		mdtidlist.add("9999" + mdtid);
		StdLostReportExample stdLostReportExample = new StdLostReportExample();
		stdLostReportExample.createCriteria().andMdtidIn(mdtidlist).andStatusEqualTo(1);
		List<StdLostReport> stdLostReports = stdLostReportMapper.selectByExample(stdLostReportExample);
		return new Result(APICode.SUCCESS, stdLostReports);
	}

	@Override
	public String modifyDevicePrice(String mdtid, String promotePrice, String packagePrice) {
		BigDecimal fee = null, fee2 = null;
		try {
			fee = new BigDecimal(promotePrice);
			fee2 = new BigDecimal(packagePrice);
		} catch (NumberFormatException e) {
			return "价格格式不符";
		}
		// 修改std_deviceinfo表
		StdDeviceinfoExample stdDeviceinfoExample = new StdDeviceinfoExample();
		stdDeviceinfoExample.createCriteria().andMdtidEqualTo(mdtid).andIsdeletedEqualTo(0);
		List<StdDeviceinfo> deviceinfoList = stdDeviceinfoMapper.selectByExample(stdDeviceinfoExample);
		boolean exist = false;
		if (!CollectionUtils.isEmpty(deviceinfoList)) {
			StdDeviceinfo stdDeviceinfo = new StdDeviceinfo();
			stdDeviceinfo.setFee(fee);
			stdDeviceinfo.setFee2(fee2);
			stdDeviceinfo.setUpdatetime(new Date());
			stdDeviceinfoMapper.updateByExampleSelective(stdDeviceinfo, stdDeviceinfoExample);
			exist = true;
		}
		// 修改devicelists表
		DevicelistExample devicelistExample = new DevicelistExample();
		devicelistExample.createCriteria().andMdtidEqualTo(mdtid);
		List<Devicelist> deviceList = devicelistMapper.selectByExample(devicelistExample);
		if (!CollectionUtils.isEmpty(deviceList)) {
			Devicelist devicelist = new Devicelist();
			devicelist.setFee(fee);
			devicelist.setFee2(fee2);
			devicelist.setUpdatetime(new Date());
			devicelistMapper.updateByExampleSelective(devicelist, devicelistExample);
			exist = true;
		}
		// 修改std_iot_device表
		StdIotDeviceExample stdIotDeviceExample = new StdIotDeviceExample();
		stdIotDeviceExample.createCriteria().andImeiLike(mdtid);
		List<StdIotDevice> iotDeviceList = stdIotDeviceMapper.selectByExample(stdIotDeviceExample);
		if (!CollectionUtils.isEmpty(iotDeviceList)) {
			StdIotDevice stdIotDevice = new StdIotDevice();
			stdIotDevice.setFee(fee);
			stdIotDevice.setFee2(fee2);
			stdIotDeviceMapper.updateByExampleSelective(stdIotDevice, stdIotDeviceExample);
			exist = true;
		}

		if (!exist) {
			return "设备不存在";
		}
		return null;
	}

	@Override
	public Map<String, String> getMdtidType(String cardid) {

		Map<String, String> map = new HashMap<>();
		String type = "type";
		String mdtid = "mdtid";
		// 查询2.4G考勤卡
		String mdtid2_4 = Constant._2_4G_MDTID_PREFIX + cardid;
		DevicelistExample example2_4 = new DevicelistExample();
		example2_4.createCriteria().andMdtidEqualTo(mdtid2_4);
		List<Devicelist> list2_4 = devicelistMapper.selectByExample(example2_4);
		if (CollectionUtils.isNotEmpty(list2_4)) {
			map.put(type, Constant.Device.WHITE_CARD1);
			map.put(mdtid, mdtid2_4);
			return map;
		}
		// 查询13.56考勤卡
		String mdtid13_56 = Constant._13_56_MDTID_PREFIX + cardid;
		DevicelistExample example13_56 = new DevicelistExample();
		example13_56.createCriteria().andMdtidEqualTo(mdtid13_56);
		List<Devicelist> list13_56 = devicelistMapper.selectByExample(example13_56);
		if (CollectionUtils.isNotEmpty(list13_56)) {
			map.put(type, Constant.Device.WHITE_CARD2);
			map.put(mdtid, mdtid13_56);
			return map;
		}
		// 查询卫小宝自带考勤卡
		DevicelistExample examplewxb = new DevicelistExample();
		examplewxb.createCriteria().andCardidEqualTo(cardid);
		List<Devicelist> listwxb = devicelistMapper.selectByExample(examplewxb);
		if (CollectionUtils.isNotEmpty(listwxb)) {
			map.put(type, Constant.Device.WEIXIAOBAO);
			map.put(mdtid, listwxb.get(0).getMdtid());
			return map;
		}
		return map;
	}

	@Override
	public MqUseage selectCurrentMonthMessage(Integer type, String mdtid) {
		Date date = new Date();
		date = DateUtil.formatStringToTime(DateUtil.formatDateToString(date, "yyyy-MM"), "yyyy-MM");
		MqUseageExample useageExample = new MqUseageExample();
		useageExample.createCriteria().andUseagemonthEqualTo(date).andTypeEqualTo(type).andMdtidEqualTo(mdtid);
		List<MqUseage> useageList = mqUseageMapper.selectByExample(useageExample);
		if (CollectionUtils.isEmpty(useageList)) {
			return null;
		} else {
			return useageList.get(0);
		}
	}

	@Override
	public MqUseage selectCurrentMonthMessage(Integer type, Integer objectId) {
		Date date = new Date();
		date = DateUtil.formatStringToTime(DateUtil.formatDateToString(date, "yyyy-MM"), "yyyy-MM");
		MqUseageExample useageExample = new MqUseageExample();
		useageExample.createCriteria().andUseagemonthEqualTo(date).andTypeEqualTo(type).andObjectidEqualTo(objectId);
		List<MqUseage> useageList = mqUseageMapper.selectByExample(useageExample);
		if (CollectionUtils.isEmpty(useageList)) {
			return null;
		} else {
			return useageList.get(0);
		}
	}

	@Override
	public void sendInstructions(String mdtid, Integer type) {
		if (StringUtils.isBlank(mdtid)) {
			throw new OpServiceException("设备号不能为空");
		}
		// 查询设备号是否已绑定学生
		StdObjectinfo objectinfo = studentService.selectStudent(mdtid);
		if (objectinfo == null) {
			throw new OpServiceException("该设备未绑定学生");
		}
		// 发送指令
		DeviceMessage deviceMessage = messageFactory.createMessage(type);
		if(deviceMessage == null) {
			throw new OpServiceException("发送类型不存在");
		}
		deviceMessage.setImei(mdtid);
		deviceDeal.sendInstructions(deviceMessage);
	}

	@Override
	public List<MqUseage> listCurrentMonthMessage(String mdtid) {
		Date date = new Date();
		date = DateUtil.formatStringToTime(DateUtil.formatDateToString(date, "yyyy-MM"), "yyyy-MM");
		MqUseageExample useageExample = new MqUseageExample();
		useageExample.createCriteria().andUseagemonthEqualTo(date).andMdtidEqualTo(mdtid);
		return mqUseageMapper.selectByExample(useageExample);
	}

	@Override
	public List<MqUseage> listCurrentMonthMessage(Integer objectId) {
		Date date = new Date();
		date = DateUtil.formatStringToTime(DateUtil.formatDateToString(date, "yyyy-MM"), "yyyy-MM");
		MqUseageExample useageExample = new MqUseageExample();
		useageExample.createCriteria().andUseagemonthEqualTo(date).andObjectidEqualTo(objectId);
		return mqUseageMapper.selectByExample(useageExample);
	}

}
